From 826fe4f11beaeb26baf0dc31388805376cb99a9f Mon Sep 17 00:00:00 2001 From: Yohan Chalier Date: Wed, 5 Jul 2023 22:10:20 +0200 Subject: [PATCH] Initial commit --- .gitignore | 16 + LICENSE.txt | 674 ++++++++++++++++++ MANIFEST.in | 3 + README.md | 50 ++ beatviewer.py | 4 + beatviewer/__init__.py | 147 ++++ beatviewer/__main__.py | 3 + beatviewer/audio_source/__init__.py | 0 beatviewer/audio_source/audio_source.py | 42 ++ beatviewer/audio_source/file_audio_source.py | 63 ++ beatviewer/audio_source/live_audio_source.py | 70 ++ beatviewer/beat_handler_process.py | 68 ++ beatviewer/beat_tracker.py | 132 ++++ beatviewer/beat_tracker_process.py | 63 ++ beatviewer/config.py | 103 +++ beatviewer/graph.py | 102 +++ beatviewer/handlers/__init__.py | 21 + beatviewer/handlers/beep.py | 40 ++ beatviewer/handlers/galaxy.py | 242 +++++++ beatviewer/handlers/pygame_handler.py | 54 ++ beatviewer/handlers/rectangles.py | 144 ++++ beatviewer/handlers/socket.py | 123 ++++ beatviewer/handlers/tunnel.py | 72 ++ beatviewer/handlers/warp.py | 229 ++++++ beatviewer/handlers/waves.py | 102 +++ beatviewer/handlers/web_handler.py | 91 +++ beatviewer/pipelines/__init__.py | 0 beatviewer/pipelines/audio_stream_pipeline.py | 37 + .../pipelines/beat_tracking_pipeline.py | 149 ++++ beatviewer/pipelines/pipeline.py | 50 ++ .../pipelines/tempo_estimation_pipeline.py | 121 ++++ beatviewer/tools/__init__.py | 9 + beatviewer/tools/annotator.py | 269 +++++++ beatviewer/tools/directogram.py | 134 ++++ beatviewer/tools/dummy.py | 97 +++ beatviewer/tools/tool.py | 15 + beatviewer/video/__init__.py | 0 beatviewer/video/video_buffer.py | 94 +++ beatviewer/video/video_output.py | 36 + beatviewer/video/video_player.py | 58 ++ beatviewer/video/video_reader.py | 70 ++ beatviewer/video/video_stream.py | 24 + beatviewer/web/fireworks.html | 179 +++++ beatviewer/web/fluid.html | 338 +++++++++ beatviewer/web/socket.js | 92 +++ config.txt | 179 +++++ obs_beatviewer.py | 493 +++++++++++++ requirements.txt | 11 + setup.py | 34 + 49 files changed, 5147 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE.txt create mode 100644 MANIFEST.in create mode 100644 README.md create mode 100644 beatviewer.py create mode 100644 beatviewer/__init__.py create mode 100644 beatviewer/__main__.py create mode 100644 beatviewer/audio_source/__init__.py create mode 100644 beatviewer/audio_source/audio_source.py create mode 100644 beatviewer/audio_source/file_audio_source.py create mode 100644 beatviewer/audio_source/live_audio_source.py create mode 100644 beatviewer/beat_handler_process.py create mode 100644 beatviewer/beat_tracker.py create mode 100644 beatviewer/beat_tracker_process.py create mode 100644 beatviewer/config.py create mode 100644 beatviewer/graph.py create mode 100644 beatviewer/handlers/__init__.py create mode 100644 beatviewer/handlers/beep.py create mode 100644 beatviewer/handlers/galaxy.py create mode 100644 beatviewer/handlers/pygame_handler.py create mode 100644 beatviewer/handlers/rectangles.py create mode 100644 beatviewer/handlers/socket.py create mode 100644 beatviewer/handlers/tunnel.py create mode 100644 beatviewer/handlers/warp.py create mode 100644 beatviewer/handlers/waves.py create mode 100644 beatviewer/handlers/web_handler.py create mode 100644 beatviewer/pipelines/__init__.py create mode 100644 beatviewer/pipelines/audio_stream_pipeline.py create mode 100644 beatviewer/pipelines/beat_tracking_pipeline.py create mode 100644 beatviewer/pipelines/pipeline.py create mode 100644 beatviewer/pipelines/tempo_estimation_pipeline.py create mode 100644 beatviewer/tools/__init__.py create mode 100644 beatviewer/tools/annotator.py create mode 100644 beatviewer/tools/directogram.py create mode 100644 beatviewer/tools/dummy.py create mode 100644 beatviewer/tools/tool.py create mode 100644 beatviewer/video/__init__.py create mode 100644 beatviewer/video/video_buffer.py create mode 100644 beatviewer/video/video_output.py create mode 100644 beatviewer/video/video_player.py create mode 100644 beatviewer/video/video_reader.py create mode 100644 beatviewer/video/video_stream.py create mode 100644 beatviewer/web/fireworks.html create mode 100644 beatviewer/web/fluid.html create mode 100644 beatviewer/web/socket.js create mode 100644 config.txt create mode 100644 obs_beatviewer.py create mode 100644 requirements.txt create mode 100644 setup.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c553e1b --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +__pycache__ +*.pyc +*.log +*.egg-info +dist +*.bin +*.wav +*.tsv +*.webm +.ipynb_checkpoints +*.mp4 +*.json +*.gif +*.mp3 +build/ +assets/ \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..e72bfdd --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..67fa056 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,3 @@ +include LICENSE +include README.md +recursive-include beatviewer/web * \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..a4259e0 --- /dev/null +++ b/README.md @@ -0,0 +1,50 @@ +# BeatViewer + +*BeatViewer* is a [Python](https://www.python.org/) program that analyzes an audio stream, extracts [onsets](https://en.wikipedia.org/wiki/Onset_(audio)), [tempo](https://en.wikipedia.org/wiki/Tempo) and [beats](https://en.wikipedia.org/wiki/Beat_(music)), and creates [visuals](https://en.wikipedia.org/wiki/VJing) from them in real time. Feature extraction relies on state-of-the-art [beat tracking algorithms](https://michaelkrzyzaniak.com/Research/Swarms_Preprint.pdf). Visuals are rendered via [Pygame](https://www.pygame.org/news) or external programs such as [OBS Studio](https://obsproject.com/) or any [WebSocket](https://en.wikipedia.org/wiki/WebSocket) client. + +For a detailed narration of the birth of the project, watch the [associated video](https://www.youtube.com/watch?v=qv1uJQW-Cpc) (in French, English subtitles are coming). + +## Requirements + +This program requires a working installation of [Python 3](https://www.python.org/). Tools such as [FFmpeg](https://ffmpeg.org/) and [OBS Studio](https://obsproject.com/) are recommended. + +## Installation + +1. Download the [latest release](https://github.com/ychalier/beatviewer/releases) +2. Install it with `pip`: + ```console + pip install ~/Downloads/beatviewer-1.0.0.tar.gz + ``` + +Some resources (OBS script, tools, JS visuals) are available through direct download and are attached to the [latest release](https://github.com/ychalier/beatviewer/releases). + +## Configuration + +Here is a summary of what you'll need to get started. For more options (file output, tracking parameters, etc.) please refer to the [wiki](https://github.com/ychalier/beatviewer/wiki/). + +### Audio Source Selection + +By default, BeatViewer uses the default audio input. You can specify an audio device using the `-a ` parameter. You can get a list of audio devices by using the `-l` flag. You can also execute the module offline, by passing the path to an audio file with the `-f` argument (for now, only WAVE file are supported). + +### Visualizer Selection + +By default, no visualizer is attached to the tracker, it simply prints dots to stdout when a beat occurs. You can specify a visualizer by typing its name after the beat tracking arguments: + +```console +python -m beatviewer +``` + +For a quick test, you can try the `galaxy` visualizer. You'll find a list with more options and instructions on the [wiki](https://github.com/ychalier/beatviewer/wiki/). + +## Contributing + +Contributions are welcomed. For now, performance enhancements and addition of new visualizers are mostly needed. Do not hesitate to submit a pull request with your changes! + +## License + +This project is licensed under the GPL-3.0 license. + +## Troubleshooting + +Submit bug reports and feature suggestions in the [issue tracker](https://github.com/ychalier/beatviewer/issues/new/choose). + diff --git a/beatviewer.py b/beatviewer.py new file mode 100644 index 0000000..9944d5e --- /dev/null +++ b/beatviewer.py @@ -0,0 +1,4 @@ +from beatviewer import main + +if __name__ == "__main__": + main() diff --git a/beatviewer/__init__.py b/beatviewer/__init__.py new file mode 100644 index 0000000..0717bbe --- /dev/null +++ b/beatviewer/__init__.py @@ -0,0 +1,147 @@ +import argparse +import multiprocessing +import logging +import os +import time + +import sounddevice + +from .handlers import HANDLER_LIST +from .tools import TOOL_LIST +from .beat_tracker import BeatTracker +from .beat_tracker_process import BeatTrackerProcess +from .config import Config +from .audio_source.live_audio_source import LiveAudioSource +from .audio_source.file_audio_source import FileAudioSource + + +def print_table(table, padx=4): + for i in range(len(table)): + table[i] = list(map(str, table[i])) + widths = [0] * len(table[0]) + for row in table: + for j, col in enumerate(row): + widths[j] = max(widths[j], len(col)) + for row in table: + for j, col in enumerate(row): + print(col, end=" " * (widths[j] - len(col) + padx)) + print("") + + +def get_action_tool(args): + for cls in TOOL_LIST: + if cls.NAME == args.action: + return cls.from_args(args) + return None + + +def get_action_handler(args, conn): + for cls in HANDLER_LIST: + if cls.NAME == args.action: + return cls.from_args(conn, args) + return None + + +def print_audio_device_list(): + hostapis_info = sounddevice.query_hostapis() + devices_info = sounddevice.query_devices() + table = [] + default_device = hostapis_info[0]["default_input_device"] + for device in devices_info: + if device["max_input_channels"] == 0: + continue + host = hostapis_info[device["hostapi"]] + table.append([ + str(device["index"]) + ("<" if device["index"] == default_device else ""), + f"{device['max_input_channels']} in, {device['max_output_channels']} out", + f"{device['default_low_input_latency']:.2f} ms - {device['default_high_input_latency']:.2f} ms", + f"{(device['default_samplerate'] / 1000):.1f} kHz", + host["name"], + device["name"], + ]) + print_table(table) + +LOG_FORMAT = "%(asctime)s\t%(levelname)s\t%(message)s" + +def main(): + logging.basicConfig(level=logging.INFO, filename="beatviewer.log", format=LOG_FORMAT) + logging.info("Hello, World!") + logging.info("Main process has PID %d", os.getpid()) + parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument("-a", "--audio-device", type=int, default=sounddevice.default.device[0], help="Audio device index") + parser.add_argument("-l", "--list-audio-devices", action="store_true", help="Show the list of available audio devices and exit") + parser.add_argument("-f", "--audio-file", type=str, default=None, help="Path to a local audio file for 'offline' beat tracking") + parser.add_argument("-t", "--realtime", action="store_true", help="Make offline beat tracking realtime") + parser.add_argument("-g", "--graph", action="store_true", help="Plot extracted audio features for in-depth analysis") + parser.add_argument("-gf", "--graph-fps", type=float, default=30, help="Refresh rate for the audio features graph") + parser.add_argument("-c", "--config", type=str, default=None, help="Path to a configuration file (see default 'config.txt')") + parser.add_argument("-k", "--keyboard-events", action="store_true", help="Monitor keyboard events") + parser.add_argument("-r", "--record-path", type=str, default=None, help="Record the the audio stream to a local file") + parser.add_argument("-o", "--output-path", type=str, default=None, help="Export the beats, onsets and BPM data to a CSV file")# + action_subparsers = parser.add_subparsers(dest="action") + for cls in HANDLER_LIST + TOOL_LIST: + subparser = action_subparsers.add_parser(cls.NAME, formatter_class=argparse.ArgumentDefaultsHelpFormatter) + cls.add_arguments(subparser) + + args = parser.parse_args() + if args.list_audio_devices: + print_audio_device_list() + parser.exit(0) + + tool = get_action_tool(args) + if tool is not None: + tool.run() + parser.exit(0) + + if args.config is not None: + logging.info("Loading config from %s", args.config) + config = Config.from_file(args.config) + else: + logging.info("Using default config") + config = Config() + + if args.audio_file is None: + audio_source = LiveAudioSource(config, args.audio_device, args.record_path) + else: + audio_source = FileAudioSource(config, args.audio_file, realtime=args.realtime, record_path=args.record_path) + + tracker_kwargs = { + "show_graph": args.graph, + "graph_fps": args.graph_fps, + "keyboard_events": args.keyboard_events, + "output_path": args.output_path, + } + + if args.action is None: + def beat_callback(): + print(".", end="", flush=True) + BeatTracker(config, audio_source, beat_callback=beat_callback, **tracker_kwargs).run() + else: + conn1, conn2 = multiprocessing.Pipe() + tracker = BeatTrackerProcess(config, audio_source, conn1, **tracker_kwargs) + handler = get_action_handler(args, conn2) + logging.info("Starting tracker") + tracker.start() + logging.info("Starting handler") + handler.start() + logging.info("Entering main loop") + try: + while True: + time.sleep(1) + if not tracker.is_alive(): + logging.info("Tracker process is not alive, breaking main loop") + break + if not handler.is_alive(): + logging.info("Handler process is not alive, breaking main loop") + break + except KeyboardInterrupt: + pass + finally: + logging.info("Killing tracker and handler") + tracker.kill() + handler.kill() + logging.info("Joining tracker and handler") + tracker.join() + handler.join() + + logging.info("Goodbye!") \ No newline at end of file diff --git a/beatviewer/__main__.py b/beatviewer/__main__.py new file mode 100644 index 0000000..49fd8d3 --- /dev/null +++ b/beatviewer/__main__.py @@ -0,0 +1,3 @@ +from beatviewer import main + +main() \ No newline at end of file diff --git a/beatviewer/audio_source/__init__.py b/beatviewer/audio_source/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/beatviewer/audio_source/audio_source.py b/beatviewer/audio_source/audio_source.py new file mode 100644 index 0000000..fedc491 --- /dev/null +++ b/beatviewer/audio_source/audio_source.py @@ -0,0 +1,42 @@ +import logging +import wave + + +class AudioSource: + """Interface for audio source signal. It wraps utilities for updating an + array of audio samples and recording them to a local file. + """ + + def __init__(self, config, sampling_rate, record_path=None): + logging.info( + "Creating audio source, with sampling rate %d Hz", + sampling_rate + ) + self.config = config + self.sampling_rate = sampling_rate + self.record_path = record_path + self.record_file = None + self.active = True + + def setup(self): + logging.info("Setting up audio source") + if self.record_path is not None: + self.record_file = wave.open(self.record_path, "wb") + self.record_file.setnchannels(1) + self.record_file.setsampwidth(2) + self.record_file.setframerate(self.sampling_rate) + + def _update_window(self, window): + raise NotImplementedError + + def update_window(self, window): + logging.debug("Updating audio source window") + self._update_window(window) + if self.record_file is not None: + i = self.config.audio_window_size - self.config.audio_hop_size + self.record_file.writeframes(window[i:].astype("= self.window_update_period: + self.last_window_update = now + break + pass + if self.i >= self.data.shape[0]: + self.active = False + logging.info("Reached end of audio file source") + return + k = self.config.audio_window_size - self.config.audio_hop_size + window[:k] = window[self.config.audio_hop_size:] + for j in range(self.config.audio_hop_size): + if self.i >= self.data.shape[0]: + window[k + j] = 0 + else: + window[k + j] = int(sum(self.data[self.i]) / self.data.shape[1]) + self.i += 1 + self.pbar.update() + + def close(self): + self.pbar.close() \ No newline at end of file diff --git a/beatviewer/audio_source/live_audio_source.py b/beatviewer/audio_source/live_audio_source.py new file mode 100644 index 0000000..b65b4d7 --- /dev/null +++ b/beatviewer/audio_source/live_audio_source.py @@ -0,0 +1,70 @@ +import logging +import time + +import numpy +import sounddevice + +from .audio_source import AudioSource + + +class LiveAudioSource(AudioSource): + """Load audio frames from an audio input device. Multichannel signals are + averaged to a mono signal. + """ + + def __init__(self, config, device_index, record_path=None): + logging.info( + "Creating live audio source for device index %d", + device_index + ) + self.device_index = device_index + self.device_info = sounddevice.query_devices(self.device_index, "input") + self.channels = int(self.device_info["max_input_channels"]) + self.stream = None + self.overflow_ts = None + self.stats_overflowing = 0 + self.stats_total = 0 + AudioSource.__init__( + self, + config, + int(self.device_info["default_samplerate"]), + record_path=record_path + ) + + def setup(self): + logging.info("Setting up live audio source") + AudioSource.setup(self) + self.stream = sounddevice.InputStream( + device=self.device_index, + channels=self.channels, + samplerate=self.sampling_rate, + blocksize=self.config.audio_hop_size, + dtype="int16" + ) + self.stream.start() + + def _update_window(self, window): + data, overflowed = self.stream.read(frames=self.config.audio_hop_size) + if overflowed: + self.stats_overflowing += 1 + if self.overflow_ts is None: + self.overflow_ts = time.time() + self.stats_total += 1 + if self.overflow_ts is not None and time.time() - self.overflow_ts > 1: + logging.warning( + "Audio stream lost %d chunks of %d (%.0f%%) in the last second", + self.stats_overflowing, + self.stats_total, + 100 * self.stats_overflowing / self.stats_total + ) + self.overflow_ts = None + self.stats_total = 0 + self.stats_overflowing = 0 + n = self.config.audio_window_size - self.config.audio_hop_size + window[:n] = window[self.config.audio_hop_size:] + window[n:] = (numpy.sum(data, axis=1) / data.shape[1]).astype("int16") + + def close(self): + logging.info("Closing live audio source") + AudioSource.close(self) + self.stream.abort() \ No newline at end of file diff --git a/beatviewer/beat_handler_process.py b/beatviewer/beat_handler_process.py new file mode 100644 index 0000000..6c9e0a0 --- /dev/null +++ b/beatviewer/beat_handler_process.py @@ -0,0 +1,68 @@ +import logging +import multiprocessing + +from .beat_tracker_process import BeatTrackerProcess + + +class BeatHandlerProcess(multiprocessing.Process): + + NAME = "default" + + def __init__(self, pipe): + self.pipe = pipe + self.running = True + super(BeatHandlerProcess, self).__init__() + logging.info("Using beat handler class %s", self.__class__.__name__) + + @staticmethod + def add_arguments(parser): + pass + + @classmethod + def from_args(cls, pipe, args): + return cls(pipe) + + @classmethod + def from_keys(cls, pipe, args, args_keys, kwargs_keys): + return cls(pipe, *[getattr(args, key) for key in args_keys], **{key: getattr(args, key) for key in kwargs_keys}) + + def setup(self): + logging.info("Setting up beat handler") + + def loop(self): + pass + + def close(self): + logging.info("Closing beat handler") + + def handle_beat(self): + pass + + def handle_onset(self): + pass + + def handle_bpm(self, bpm): + pass + + def run(self): + log_format = "%(asctime)s\t%(levelname)s\tHandler: %(message)s" + logging.basicConfig(level=logging.INFO, filename="beatviewer.log", format=log_format) + logging.info("Starting beat handler process with PID %d", self.pid) + self.setup() + logging.info("Done setting up beat handler") + try: + while self.running: + if self.pipe.poll(): + event_flag, event_frame, event_time, event_value = self.pipe.recv() + if event_flag == BeatTrackerProcess.FLAG_BEAT: + self.handle_beat() + elif event_flag == BeatTrackerProcess.FLAG_ONSET: + self.handle_onset() + elif event_flag == BeatTrackerProcess.FLAG_BPM: + self.handle_bpm(event_value) + self.loop() + except KeyboardInterrupt: + self.running = False + finally: + self.close() + logging.info("Beat handler process has finished") diff --git a/beatviewer/beat_tracker.py b/beatviewer/beat_tracker.py new file mode 100644 index 0000000..3a5020e --- /dev/null +++ b/beatviewer/beat_tracker.py @@ -0,0 +1,132 @@ +import logging + +import keyboard + +from .graph import Graph +from .pipelines.pipeline import Pipeline + + +class BeatTracker(Pipeline): + + def __init__( + self, + config, + audio_source, + onset_callback=None, + beat_callback=None, + bpm_callback=None, + show_graph=False, + graph_size=512, + graph_fps=30, + keyboard_events=False, + output_path=None + ): + logging.info("Creating beat tracker") + Pipeline.__init__(self, config, audio_source) + self.onset_callback = onset_callback + self.beat_callback = beat_callback + self.bpm_callback = bpm_callback + self.show_graph = show_graph + self.graph = None + self.graph_size = graph_size + self.graph_fps = graph_fps + self.keybord_events = keyboard_events + self.sampling_rate = None + self.sampling_rate_oss = None + self.output_path = output_path + self.output_file = None + + def setup(self): + logging.info("Setting up beat tracker") + Pipeline.setup(self) + self.sampling_rate = self.audio_source.sampling_rate + self.sampling_rate_oss = self.sampling_rate / self.config.audio_hop_size + if self.show_graph: + self.graph = Graph(self, self.graph_size, self.graph_fps) + self.graph.start() + if self.output_path is not None: + self.output_file = open(self.output_path, "w") + self.output_file.write("event_flag\tevent_frame\tevent_time\tevent_value\n") + self.output_file.write("SAMPLING_RATE_OSS\t0\t0\t%f\n" % self.sampling_rate_oss) + + def close(self): + logging.info("Closing beat tracker") + if self.show_graph: + self.graph.terminate() + if self.show_graph: + self.graph.join() + if self.output_path is not None: + self.output_file.close() + + def check_keyboard_events(self): + if keyboard.is_pressed(self.config.key_trigger_beats_earlier): + if self.config.bps_epsilon_t < self.config.bps_buffer_size - 1: + self.config.bps_epsilon_t += 1 + print("Triggering beats earlier (%d)" % self.config.bps_epsilon_t) + elif keyboard.is_pressed(self.config.key_trigger_beats_later): + if self.config.bps_epsilon_t > 0: + self.config.bps_epsilon_t -= 1 + print("Triggering beats later (%d)" % self.config.bps_epsilon_t) + elif keyboard.is_pressed(self.config.key_set_mode_regular): + self.mode = self.MODE_REGULAR + print("Changing mode to REGULAR") + elif keyboard.is_pressed(self.config.key_set_mode_tempo_locked): + self.mode = self.MODE_TEMPO_LOCKED + print("Changing mode to TEMPO_LOCKED") + + def update(self): + logging.debug("Updating beat tracker") + Pipeline.update(self) + if self.onset_flag: + self.handle_onset() + if self.beat_flag: + self.handle_beat() + if self.bpm_flag: + self.handle_bpm() + + def write_output_line(self, key, value=None): + if value is None: + self.output_file.write("%s\t%d\t%.3f\t\n" % ( + key, + self.frame_index, + self.frame_index / self.sampling_rate_oss)) + else: + self.output_file.write("%s\t%d\t%.3f\t%.2f\n" % ( + key, + self.frame_index, + self.frame_index / self.sampling_rate_oss, + value)) + + def handle_onset(self): + if self.output_path is not None: + self.write_output_line("ONSET") + if self.onset_callback is not None: + self.onset_callback() + + def handle_beat(self): + if self.output_path is not None: + self.write_output_line("BEAT") + if self.beat_callback is not None: + self.beat_callback() + + def handle_bpm(self): + if self.output_path is not None: + self.write_output_line("BPM", self.bpm) + if self.bpm_callback is not None: + self.bpm_callback(self.bpm) + + def run(self): + self.setup() + logging.info("Done setting up beat tracker") + i = 0 + while self.running and self.active: + i += 1 + try: + if i == 10: + i = 0 + if self.keybord_events: + self.check_keyboard_events() + self.update() + except KeyboardInterrupt: + break + self.close() \ No newline at end of file diff --git a/beatviewer/beat_tracker_process.py b/beatviewer/beat_tracker_process.py new file mode 100644 index 0000000..c625ec9 --- /dev/null +++ b/beatviewer/beat_tracker_process.py @@ -0,0 +1,63 @@ +import logging +import multiprocessing + +from .beat_tracker import BeatTracker + +class BeatTrackerProcess(multiprocessing.Process, BeatTracker): + + FLAG_BEAT = 0 + FLAG_ONSET = 1 + FLAG_BPM = 2 + + COMMAND_CONFIG = 0 + + def __init__(self, + config, + audio_source, + pipe, + **kwargs + ): + self.pipe = pipe + multiprocessing.Process.__init__(self) + BeatTracker.__init__(self, config, audio_source, **kwargs) + + def send(self, flag, value=None): + self.pipe.send((flag, self.frame_index, self.frame_index / self.sampling_rate_oss, value)) + + def handle_beat(self): + BeatTracker.handle_beat(self) + if self.output_path is not None: + self.output_file.flush() + self.send(self.FLAG_BEAT) + + def handle_onset(self): + BeatTracker.handle_onset(self) + if self.output_path is not None: + self.output_file.flush() + self.send(self.FLAG_ONSET) + + def handle_bpm(self): + BeatTracker.handle_bpm(self) + if self.output_path is not None: + self.output_file.flush() + self.send(self.FLAG_BPM, self.bpm) + + def update_commands(self): + while self.pipe.poll(): + command = self.pipe.recv() + if command[0] == self.COMMAND_CONFIG: + self.config.update(command[1], command[2]) + print("Updating configuration: %s=%s" % command) + else: + print("BeatTrackerProcess received an unknown command: %s" % command[0]) + + def update(self): + BeatTracker.update(self) + self.update_commands() + + def run(self): + log_format = "%(asctime)s\t%(levelname)s\tTracker: %(message)s" + logging.basicConfig(level=logging.INFO, filename="beatviewer.log", format=log_format) + logging.info("Starting beat tracker process with PID %d", self.pid) + BeatTracker.run(self) + logging.info("Beat tracker process has finished") \ No newline at end of file diff --git a/beatviewer/config.py b/beatviewer/config.py new file mode 100644 index 0000000..02e0836 --- /dev/null +++ b/beatviewer/config.py @@ -0,0 +1,103 @@ +class Config: + + def __init__( + self, + audio_window_size=1024, + audio_hop_size=128, + compression_gamma=1, + noise_cancellation_level=-74, + hamming_window_size=15, + oss_buffer_size=1024, + onset_threshold=0.1, + onset_threshold_min=5.0, + oss_window_size=2048, + oss_hop_size=128, + frequency_domain_compression=.5, + min_bpm_detection=50, + max_bpm_detection=210, + tempo_candidates=10, + tempo_accumulator_decay=.9, + tempo_accumulator_gaussian_width=10, + min_bpm_rescaled=90, + max_bpm_rescaled=180, + cbss_eta=300, + cbss_alpha=0.9, + bps_buffer_size=1024, + bps_epsilon_o=0, + bps_epsilon_r=0, + bps_epsilon_t=20, + bps_gaussian_width=10, + cbss_buffer_size=512, + bps_cooldown_ratio=0.4, + key_trigger_beats_earlier="page up", + key_trigger_beats_later="page down", + key_set_mode_regular="f9", + key_set_mode_tempo_locked="f10", + ): + + # OSS Computation + self.audio_window_size = audio_window_size + self.audio_hop_size = audio_hop_size + self.compression_gamma = compression_gamma + self.noise_cancellation_threshold = 10 ** (noise_cancellation_level / 20) * self.audio_window_size + self.hamming_window_size = hamming_window_size + + # Onset Detection + self.oss_buffer_size = oss_buffer_size + self.onset_threshold = onset_threshold + self.onset_threshold_min = onset_threshold_min + + # Tempo Detection + self.oss_window_size = oss_window_size + self.oss_hop_size = oss_hop_size + self.frequency_domain_compression = frequency_domain_compression + self.min_bpm_detection = min_bpm_detection + self.max_bpm_detection = max_bpm_detection + self.tempo_candidates = tempo_candidates + self.tempo_accumulator_decay = tempo_accumulator_decay + self.tempo_accumulator_gaussian_width = tempo_accumulator_gaussian_width + self.min_bpm_rescaled = min_bpm_rescaled + self.max_bpm_rescaled = max_bpm_rescaled + + # CBSS Computation + self.cbss_buffer_size = cbss_buffer_size + self.cbss_eta = cbss_eta + self.cbss_alpha = cbss_alpha + + # BPS Computation + self.bps_epsilon_o = bps_epsilon_o + self.bps_epsilon_r = bps_epsilon_r + self.bps_epsilon_t = bps_epsilon_t + self.bps_gaussian_width = bps_gaussian_width + self.bps_buffer_size = bps_buffer_size + self.bps_cooldown_ratio = bps_cooldown_ratio + + # Keys + self.key_trigger_beats_earlier = key_trigger_beats_earlier + self.key_trigger_beats_later = key_trigger_beats_later + self.key_set_mode_regular = key_set_mode_regular + self.key_set_mode_tempo_locked = key_set_mode_tempo_locked + + @classmethod + def from_file(cls, path): + kwargs = {} + with open(path, "r", encoding="utf8") as file: + for line in file.readlines(): + lstrip = line.strip() + if lstrip == "": + continue + if lstrip.startswith("#"): + continue + argname, *argvals = lstrip.split() + argval = " ".join(argvals) + try: + kwargs[argname] = int(argval) + except ValueError: + try: + kwargs[argname] = float(argval) + except ValueError: + kwargs[argname] = str(argval) + return cls(**kwargs) + + def update(self, key, value): + setattr(self, key, value) \ No newline at end of file diff --git a/beatviewer/graph.py b/beatviewer/graph.py new file mode 100644 index 0000000..333c254 --- /dev/null +++ b/beatviewer/graph.py @@ -0,0 +1,102 @@ +import logging +import threading +import warnings + +import matplotlib.animation +import matplotlib.pyplot +import numpy + + +class Graph(threading.Thread): + """A graph plotting realtime data from a beat tracker. Plots OSS and CBSS + signals, BPS predicted signal, shows BPM and estimated phase. Everything + is packed in a thread to be concurrent to original computation. + """ + + def __init__(self, beat_tracker, visualizer_size, fps): + threading.Thread.__init__(self, daemon=True) + self.tracker = beat_tracker + self.size = visualizer_size + self.fps = fps + self.figure = None + self.axis = None + self.plot_oss = None + self.plot_oss_mean = None + self.plot_oss_threshold = None + self.plot_cbss = None + self.plot_bps = None + self.plot_detection_length = None + self.plot_beat_trigger_index = None + self.text_bpm = None + self.animation = None + + def run(self): + logging.info("Starting graph thread with ID %d", threading.get_ident()) + + warnings.filterwarnings("ignore") + figure, axis = matplotlib.pyplot.subplots(1, 1) + self.figure = figure + + # Force the user to use ^C to close the program + self.figure.canvas.manager.window.overrideredirect(1) + + self.axis = axis + self.axis.set_xlim(0, 2 * self.size - 1) + self.axis.set_ylim(0, 1.1) + xticks = range(0, 2 * self.size, 2 ** (round(numpy.log2(self.size)) - 2)) + self.axis.set_xticks(xticks) + self.axis.set_xticklabels(["%.1fs" % ((x - self.size) / self.tracker.sampling_rate_oss) for x in xticks]) + self.axis.spines["top"].set_visible(False) + self.axis.spines["right"].set_visible(False) + self.axis.spines["left"].set_visible(False) + self.axis.axes.get_yaxis().set_visible(False) + + self.plot_oss = self.axis.plot([0] * self.size, label="OSS")[0] + self.plot_oss_mean = self.axis.plot([0, self.size - 1], [self.tracker.oss_mean, self.tracker.oss_mean], "-", label="OSS mean")[0] + self.plot_oss_threshold = self.axis.plot([0, self.size - 1], [self.tracker.oss_threshold, self.tracker.oss_threshold], "-", label="OSS threshold")[0] + self.plot_cbss = self.axis.plot(self.tracker.cbss_buffer[-self.size:], label="CBSS")[0] + self.plot_bps = self.axis.plot(range(self.size, 2 * self.size), self.tracker.cbss_buffer[-self.size:], "--", label="BPS")[0] + self.plot_detection_length = self.axis.plot([0, 0], [0, 0], label="Δt")[0] + self.plot_beat_trigger_index = self.axis.plot([self.size + self.tracker.config.bps_epsilon_t, self.size + self.tracker.config.bps_epsilon_t], [0, 1], label="εt")[0] + self.text_bpm = self.axis.text(self.size, 1.03, "%.2f" % (60 * self.tracker.sampling_rate_oss / self.tracker.tempo_lag), ha="center") + + self.axis.legend(loc="upper right") + + def update(frame, *fargs): + max_oss = .1 + if len(self.tracker.oss_buffer[-self.size:]): + max_oss = max(self.tracker.oss_buffer[-self.size:]) + vmax_l = max( + .1, + max_oss, + max(self.tracker.cbss_buffer[-self.size:]) + ) + vmax_r = max( + .1, + max(self.tracker.bps_buffer[:self.size]) + ) + oss_values = self.tracker.oss_buffer[-self.size:] + if len(oss_values) < self.size: + oss_values = [0] * (self.size - len(oss_values)) + oss_values + self.plot_oss.set_ydata(list(map(lambda y: y / vmax_l, oss_values))) + self.plot_oss_mean.set_ydata([self.tracker.oss_mean / vmax_l, self.tracker.oss_mean / vmax_l]) + self.plot_oss_threshold.set_ydata([self.tracker.oss_threshold / vmax_l, self.tracker.oss_threshold / vmax_l]) + self.plot_cbss.set_ydata(list(map(lambda y: y / vmax_l, self.tracker.cbss_buffer[-self.size:]))) + self.plot_bps.set_ydata(list(map(lambda y: y / vmax_r, self.tracker.bps_buffer[:self.size]))) + self.plot_detection_length.set_data([self.size - self.tracker.phi_max - self.tracker.tempo_lag, self.size - self.tracker.phi_max], [self.tracker.cbss_buffer[-self.tracker.phi_max] / vmax_l, self.tracker.cbss_buffer[-self.tracker.phi_max] / vmax_l]) + self.text_bpm.set_text("%.2f" % (60 * self.tracker.sampling_rate_oss / self.tracker.tempo_lag)) + self.plot_beat_trigger_index.set_xdata([self.size + self.tracker.config.bps_epsilon_t, self.size + self.tracker.config.bps_epsilon_t]) + return self.plot_oss, self.plot_cbss, self.plot_bps, self.plot_oss_mean, self.plot_oss_threshold, self.plot_detection_length, self.plot_beat_trigger_index, self.text_bpm + + self.animation = matplotlib.animation.FuncAnimation(self.figure, update, blit=True, interval=round(1000 / self.fps)) + matplotlib.pyplot.show() + + def terminate(self): + logging.info("Closing graph thread") + # Matplotlib does not behave well when not in the main thread. + # This hacks helps for it to close nicely. + root = self.figure.canvas.manager.window._root() + matplotlib.pyplot.close() + root.quit() + + \ No newline at end of file diff --git a/beatviewer/handlers/__init__.py b/beatviewer/handlers/__init__.py new file mode 100644 index 0000000..136f875 --- /dev/null +++ b/beatviewer/handlers/__init__.py @@ -0,0 +1,21 @@ +from .beep import Beep +from .web_handler import Fluid +from .web_handler import Fireworks +from .galaxy import Galaxy +from .rectangles import Rectangles +from .socket import Socket +from .tunnel import Tunnel +from .warp import Warp +from .waves import Waves + +HANDLER_LIST = [ + Beep, + Fireworks, + Fluid, + Galaxy, + Rectangles, + Socket, + Tunnel, + Warp, + Waves +] \ No newline at end of file diff --git a/beatviewer/handlers/beep.py b/beatviewer/handlers/beep.py new file mode 100644 index 0000000..a7f4d84 --- /dev/null +++ b/beatviewer/handlers/beep.py @@ -0,0 +1,40 @@ +import os + +from ..beat_handler_process import BeatHandlerProcess + +try: + import winsound + def beep(frequency, duration): + winsound.Beep(frequency, duration) +except ImportError: + def beep(frequency, duration): + os.system(f"beep -f { frequency } -l { duration }") + + +class Beep(BeatHandlerProcess): + + NAME = "beep" + + def __init__(self, pipe, beats_only=False, onsets_only=False): + BeatHandlerProcess.__init__(self, pipe) + self.beats_only = beats_only + self.onsets_only = onsets_only + + @staticmethod + def add_arguments(parser): + parser.add_argument("-b", "--beats-only", action="store_true", help="Only beep when beats are detected") + parser.add_argument("-o", "--onsets-only", action="store_true", help="Only beep when onsets are detected") + + @classmethod + def from_args(cls, pipe, args): + return cls.from_keys(pipe, args, [], ["beats_only", "onsets_only"]) + + def handle_beat(self): + if self.onsets_only: + return + winsound.Beep(220, 20) + + def handle_onset(self): + if self.beats_only: + return + winsound.Beep(440, 10) \ No newline at end of file diff --git a/beatviewer/handlers/galaxy.py b/beatviewer/handlers/galaxy.py new file mode 100644 index 0000000..b81968c --- /dev/null +++ b/beatviewer/handlers/galaxy.py @@ -0,0 +1,242 @@ +import math +import random + +import pygame + +from .pygame_handler import PygameHandler + + +class Dot: + + SPRITE_SIZE = 64 + + def __init__(self, vmax, z0, base_color, base_radius, dz, blur=10): + self.vmax = vmax + self.z0 = z0 + self.base_color = base_color + self.base_radius = base_radius + self.x = 0 + self.y = 0 + self.z = 0 + self.px = 0 + self.py = 0 + self.vx = 0 + self.vy = 0 + self.ax = 0 + self.ay = 0 + self.dz = dz + self.blur = blur + self.reset(randomz=True) + self.sprite = pygame.Surface((self.SPRITE_SIZE, self.SPRITE_SIZE), pygame.SRCALPHA) + self.generate_sprite() + + def generate_sprite(self): + center = self.SPRITE_SIZE // 2 + for i in range(self.SPRITE_SIZE): + for j in range(self.SPRITE_SIZE): + t = math.sqrt(math.pow(center - i, 2) + math.pow(center - j, 2)) / center + alpha = 1 - math.pow(t, self.blur) + alpha = 255 * max(0, min(1, alpha)) + self.sprite.set_at((i, j), (*self.base_color, alpha)) + + def reset(self, randomz=False): + if randomz: + self.z = random.random() + else: + self.z = 1 + self.x = random.gauss(mu=0, sigma=0.2) / self.z0 * self.z + self.y = random.gauss(mu=0, sigma=0.2) / self.z0 * self.z + self._update_px_py() + + @property + def radius(self): + return self.base_radius / self.z + + @property + def color(self): + if self.z < .9: + return self.base_color[:] + g = (1 - self.z) / .1 + return [g * c for c in self.base_color] + + @property + def out(self): + return self.z <= 0 or self.px < 0 or self.px >= 1 or self.py < 0 or self.py >= 1 + + def _update_px_py(self): + self.px = self.x * self.z0 / self.z + .5 + self.py = self.y * self.z0 / self.z + .5 + + @property + def vnorm(self): + return (self.vx ** 2 + self.vy ** 2) ** .5 + + def push(self, direction, strength): + self.ax = strength * direction[0] + self.ay = strength * direction[1] + + def update(self, dz=0): + if dz is None: + dz = self.dz + self.z += dz + self.vx += self.ax + self.vy += self.ay + if self.vnorm > self.vmax: + self.vx /= self.vnorm / self.vmax + self.vy /= self.vnorm / self.vmax + self.x += self.vx + self.y += self.vy + self._update_px_py() + if self.out: + self.reset() + + +def generate_random_direction(previous_direction=None): + if previous_direction is None: + previous_direction = [1, 0] + x, y = previous_direction + if x == 0: + if y > 0: + theta = math.pi / 2 + else: + theta = - math.pi / 2 + else: + theta = math.atan2(y, x) + theta_mod = random.random() * math.pi - .5 * math.pi + new_theta = theta + math.pi + theta_mod + return [math.cos(new_theta), math.sin(new_theta)] + + +def generate_random_color(): + """ + https://clarkvision.com/articles/color-of-stars/ + """ + return random.choice([ + (103, 139, 201), + (118, 140, 200), + (121, 146, 200), + (111, 143, 200), + (116, 149, 200), + (120, 150, 200), + (130, 166, 200), + (138, 174, 200), + (132, 166, 201), + (148, 176, 200), + (152, 176, 200), + (161, 184, 200), + (164, 191, 200), + (184, 200, 200), + (193, 200, 193), + (199, 200, 195), + (193, 200, 192), + (200, 200, 200), + (191, 200, 173), + (200, 181, 164), + (201, 201, 165), + (200, 195, 189), + (200, 185, 162), + (200, 179, 134), + (201, 154, 112), + (200, 162, 99), + (200, 133, 65), + (200, 141, 73), + (200, 137, 84), + (200, 119, 54), + (200, 53, 46), + ]) + + +def blurred_circle(surface, dot, center): + dest_size = int(dot.radius * 5) + sprite = pygame.Surface((dest_size, dest_size), pygame.SRCALPHA) + pygame.transform.scale(dot.sprite, (dest_size, dest_size), sprite) + if dot.z >= .9: + sprite.set_alpha(255 * (1 - dot.z) / .1) + surface.blit( + sprite, + (center[0] - Dot.SPRITE_SIZE // 2, center[1] - Dot.SPRITE_SIZE // 2)) + + +class Galaxy(PygameHandler): + + NAME = "galaxy" + + def __init__( + self, + pipe, + width=1280, + height=720, + fullscreen=False, + fps=60, + n=200, + dz=0.005, + dxy=3, + z0=0.1, + vmax=0.1, + bw=False, + blur=10, + random_dz=0, + base_radius=1, + ): + PygameHandler.__init__(self, pipe, width, height, fullscreen, fps) + self.n = n + self.z0 = z0 + self.dz = dz + self.dxz = dxy + self.vmax = vmax + self.bw = bw + self.blur = blur + self.random_dz = random_dz + self.base_radius = base_radius + self.previous_direction = None + self.dots = [] + + @staticmethod + def add_arguments(parser): + PygameHandler.add_arguments(parser) + parser.add_argument("--n", type=int, default=200, help="Number of moving dots") + parser.add_argument("--z0", type=float, default=0.1, help="Z-index (between 0 and 1) of the camera plane; lower values increase the FOV") + parser.add_argument("--dz", type=float, default=0.015, help="Dot speed along the Z axis") + parser.add_argument("--dxy", type=float, default=0.02, help="Acceleration amplitude for the XY axes; greater values will make beat impacts stronger") + parser.add_argument("--vmax", type=float, default=0.05, help="Dot speed limit on the XY axes; both range from 0 to 1") + parser.add_argument("--bw", action="store_true", help="Disable colors") + parser.add_argument("--blur", type=int, default=2, help="Dot blurring factor; dots get sharper as the value increases") + parser.add_argument("--random-dz", type=float, default=0, help="Z-axis speed deviation probability") + parser.add_argument("--base-radius", type=float, default=1, help="Dot radius") + + @classmethod + def from_args(cls, pipe, args): + return cls.from_keys( + pipe, + args, + [], + PygameHandler.BASE_KWARG_KEYS + ["n", "z0", "dz", "dxy", "vmax", "bw", "blur", "random_dz", "base_radius"]) + + def setup(self): + PygameHandler.setup(self, "BeatViewer: Galaxy") + self.dots = [] + for _ in range(self.n): + if self.bw: + color = [255, 255, 255] + else: + color = generate_random_color() + dzrange = self.random_dz * self.dz + dz = self.dz + random.random() * 2 * dzrange - dzrange + dot = Dot(self.vmax, self.z0, color, self.base_radius, -dz, self.blur) + self.dots.append(dot) + + def push_dots(self): + self.previous_direction = generate_random_direction(self.previous_direction) + for dot in self.dots: + dot.push(self.previous_direction[:], self.dxz) + + def handle_beat(self): + self.push_dots() + + def update(self): + self.window.fill((0, 0, 0)) + for dot in self.dots: + dot.update(dz=None) + self.dots.sort(key=lambda d: -d.z) + for dot in self.dots: + blurred_circle(self.window, dot, (dot.px * self.width, dot.py * self.height)) diff --git a/beatviewer/handlers/pygame_handler.py b/beatviewer/handlers/pygame_handler.py new file mode 100644 index 0000000..f11200f --- /dev/null +++ b/beatviewer/handlers/pygame_handler.py @@ -0,0 +1,54 @@ +import time + +import pygame + +from ..beat_handler_process import BeatHandlerProcess + + +class PygameHandler(BeatHandlerProcess): + + BASE_KWARG_KEYS = ["fps", "width", "height", "fullscreen"] + + def __init__(self, pipe, width=1280, height=720, fullscreen=False, fps=60): + BeatHandlerProcess.__init__(self, pipe) + self.width = width + self.height = height + self.fullscreen = fullscreen + self.fps = fps + self.window = None + self.last_loop = 0 + + @staticmethod + def add_arguments(parser): + parser.add_argument("--fps", type=float, default=60, help="Framerate") + parser.add_argument("--width", type=int, default=1280, help="Window width") + parser.add_argument("--height", type=int, default=720, help="Window height") + parser.add_argument("--fullscreen", action="store_true") + + def setup(self, title=None): + flags = pygame.FULLSCREEN if self.fullscreen else 0 + self.window = pygame.display.set_mode((self.width, self.height), flags) + if title is not None: + pygame.display.set_caption(title) + + def close(self): + pygame.display.quit() + + def update(self): + raise NotImplementedError + + def loop(self): + t = time.time() + if t - self.last_loop <= 1 / self.fps: + return + self.last_loop = t + self.update() + pygame.display.flip() + for event in pygame.event.get(): + if event.type == pygame.QUIT: + self.running = False + break + elif event.type == pygame.KEYDOWN: + if event.key == pygame.K_ESCAPE: + self.running = False + break diff --git a/beatviewer/handlers/rectangles.py b/beatviewer/handlers/rectangles.py new file mode 100644 index 0000000..f794376 --- /dev/null +++ b/beatviewer/handlers/rectangles.py @@ -0,0 +1,144 @@ +import itertools +import random +import time + +import pygame + +from .pygame_handler import PygameHandler + + +def create_color_pairs(*colors): + return [(c1, c2) for c1, c2 in itertools.combinations(colors, 2) if c1 != c2] + + +PALETTES = { + None: ( + ((0, 0, 0), (255, 255, 255)), + ), + "bw": ( + ((0, 0, 0), (255, 255, 255)), + ), + "rgb": ( + ((0, 0, 0), (255, 0, 0)), + ((0, 0, 0), (0, 255, 0)), + ((0, 0, 0), (0, 0, 255)), + ), + "dark": create_color_pairs( + (53, 4, 57), + (254, 251, 255), + (86, 8, 121), + (53, 4, 57), + (114, 11, 228) + ), + "chromakey": ( + ((0, 255, 0), (53, 4, 57)), + ((0, 255, 0), (86, 8, 121)), + ((0, 255, 0), (114, 11, 228)), + ((0, 255, 0), (91, 12, 68)), + ((0, 255, 0), (254, 251, 255)), + ), + "hippy": create_color_pairs( + (49, 160, 196), + (217, 53, 192), + (117, 210, 120), + (233, 89, 89), + (231, 200, 90) + ), + "contrast": ( + ((1, 42, 52), (113, 201, 52)), + ((113, 201, 52), (1, 42, 52)), + ) +} + + +class Rectangles(PygameHandler): + + NAME = "rectangles" + + def __init__( + self, + pipe, + width=1280, + height=720, + fullscreen=False, + fps=60, + palette=None, + scale_curve=.3, + duration=5, + beat_breadth=.97, + onset_breadth=.995, + onsets=False, + ): + PygameHandler.__init__(self, pipe, width, height, fullscreen, fps) + self.palette = PALETTES[palette] + self.scale_curve = scale_curve + self.duration = duration + self.beat_breadth = beat_breadth + self.onset_breadth = onset_breadth + self.handle_onsets = onsets + + self.color_index = random.randint(0, len(self.palette) - 1) + self.bg_color = self.palette[self.color_index][0] + self.fg_color = self.palette[self.color_index][1] + self.time_between_beats = self.duration * 60 / 100 + self.rectangles = [] + + @staticmethod + def add_arguments(parser): + PygameHandler.add_arguments(parser) + parser.add_argument("--palette", type=str, default="dark", help="Choose a color palette", choices=[p for p in PALETTES if p is not None]) + parser.add_argument("--scale-curve", type=float, default=0.3, help="Power of non-linear scale progression. Values smaller than 1 produce an ease-out effect.") + parser.add_argument("--duration", type=float, default=5, help="How long a rectangle takes to go off screen, in seconds") + parser.add_argument("--beat-breadth", type=float, default=0.97, help="Relative size of inner beat rectangles. Smaller values create thicker rectangles.") + parser.add_argument("--onset-breadth", type=float, default=0.99, help="Relative size of inner onset rectangles. Smaller values create thicker rectangles.") + parser.add_argument("--onsets", action="store_true", help="Also handle onsets") + + @classmethod + def from_args(cls, pipe, args): + return cls.from_keys( + pipe, args, [], PygameHandler.BASE_KWARG_KEYS + ["palette", "scale_curve", "duration", "beat_breadth", "onset_breadth", "onsets"]) + + def change_color(self): + previous_color_index = self.color_index + while self.color_index == previous_color_index and len(self.palette) > 1: + self.color_index = random.randint(0, len(self.palette) - 1) + self.bg_color = self.palette[self.color_index][0] + self.fg_color = self.palette[self.color_index][1] + + def handle_beat(self): + self.rectangles.append((time.time(), self.beat_breadth, 1)) + self.change_color() + + def handle_onset(self): + if not self.handle_onsets: + return + self.rectangles.append((time.time(), self.onset_breadth, .5)) + + def handle_bpm(self, bpm): + self.time_between_beats = self.duration * 60 / bpm + + def setup(self): + PygameHandler.setup(self, "BeatViewer: Rectangles") + + def update(self): + self.window.fill(self.bg_color) + i = 0 + now = time.time() + while i < len(self.rectangles): + t, breadth, opacity = self.rectangles[i] + scale = ((now - t) / self.time_between_beats) ** self.scale_curve + if scale < 1.12: + width = scale * self.width + height = scale * self.height + color = ( + opacity * self.fg_color[0] + (1 - opacity) * self.bg_color[0], + opacity * self.fg_color[1] + (1 - opacity) * self.bg_color[1], + opacity * self.fg_color[2] + (1 - opacity) * self.bg_color[2], + ) + pygame.draw.rect(self.window, color, pygame.Rect((self.width - width) // 2, (self.height - height) // 2, width, height)) + width = min(breadth * width, width - 2) + height = min(breadth * height, height - 2) + pygame.draw.rect(self.window, self.bg_color, pygame.Rect((self.width - width) // 2, (self.height - height) // 2, width, height)) + i += 1 + else: + self.rectangles.pop(i) diff --git a/beatviewer/handlers/socket.py b/beatviewer/handlers/socket.py new file mode 100644 index 0000000..1d7752e --- /dev/null +++ b/beatviewer/handlers/socket.py @@ -0,0 +1,123 @@ +import asyncio +import threading +import socket + +import websockets + +from ..beat_handler_process import BeatHandlerProcess + + +class WebSocketServer(threading.Thread): + + def __init__(self, host="localhost", port=8765): + threading.Thread.__init__(self, daemon=True) + self.host = host + self.port = port + self.connections = {} + + def broadcast(self, bytes_message): + for websocket in list(self.connections.values()): + try: + async def aux(): + await websocket.send(bytes_message) + asyncio.run(aux()) + except Exception as err: + print(err, flush=True) + + def run(self): + async def ws_handler(websocket, *args): + self.connections[websocket.id] = websocket + print("WebSocket client connected:", websocket.id) + async for _ in websocket: + pass + print("WebSocket client disconnected:", websocket.id) + del self.connections[websocket.id] + async def start_server(): + print(f"WebSocket server listening at ws://{ self.host }:{ self.port }") + async with websockets.serve(ws_handler, self.host, self.port): + await asyncio.Future() + asyncio.run(start_server()) + + +class RawSocketServer(threading.Thread): + + def __init__(self, host, port): + threading.Thread.__init__(self, daemon=True) + self.host = host + self.port = port + self.s = None + self.messages = [] + self.clients = [] + self.running = True + + def broadcast(self, bytes_message): + for i, client in enumerate(self.clients): + try: + client.send(bytes_message) + except (ConnectionAbortedError, ConnectionRefusedError, ConnectionResetError): + print("Socket client disconnected") + self.clients.pop(i) + + def run(self): + self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.s.bind((self.host, self.port)) + self.s.listen(5) + print(f"Socket server listening at ws://{ self.host }:{ self.port }") + while self.running: + (clientsocket, address) = self.s.accept() + print("New client:", address) + self.clients.append(clientsocket) + self.s.close() + + +class Socket(BeatHandlerProcess): + + NAME = "socket" + + def __init__(self, pipe, host="localhost", port=8765, web=False, + mute_beats=False, mute_onsets=False, mute_bpm=False): + BeatHandlerProcess.__init__(self, pipe) + self.server = None + self.host = host + self.port = port + self.web = web + self.mute_beats = mute_beats + self.mute_onsets = mute_onsets + self.mute_bpm = mute_bpm + + @staticmethod + def add_arguments(parser): + parser.add_argument("--web", action="store_true", help="Use WebSockets protocol") + parser.add_argument("--host", type=str, default="localhost", help="Server host") + parser.add_argument("--port", type=int, default=8765, help="Server port") + parser.add_argument("--mute-beats", action="store_true", help="Do not handle beats") + parser.add_argument("--mute-onsets", action="store_true", help="Do not handle onsets") + parser.add_argument("--mute-bpm", action="store_true", help="Do not handle BPM") + + @classmethod + def from_args(cls, pipe, args): + return cls.from_keys( + pipe, args, [], + ["host", "port", "web", "mute_beats", "mute_onsets", "mute_bpm"]) + + def handle_beat(self): + if self.server is None or self.mute_beats: + return + self.server.broadcast(b"\x00\x00") + + def handle_onset(self): + if self.server is None or self.mute_onsets: + return + self.server.broadcast(b"\x00\x01") + + def handle_bpm(self, bpm): + if self.server is None or self.mute_bpm: + return + self.server.broadcast(round(bpm).to_bytes(2, "big")) + + def setup(self): + if self.web: + self.server = WebSocketServer(self.host, self.port) + else: + self.server = RawSocketServer(self.host, self.port) + self.server.start() diff --git a/beatviewer/handlers/tunnel.py b/beatviewer/handlers/tunnel.py new file mode 100644 index 0000000..a4422d3 --- /dev/null +++ b/beatviewer/handlers/tunnel.py @@ -0,0 +1,72 @@ +import time + +import pygame + +from .pygame_handler import PygameHandler + + +class Tunnel(PygameHandler): + + NAME = "tunnel" + + def __init__( + self, + pipe, + width=1280, + height=720, + fullscreen=False, + fps=60, + n=20, + z0=0.05, + ): + PygameHandler.__init__(self, pipe, width, height, fullscreen, fps) + self.n = n + self.z0 = z0 + self.bg_color = (0, 0, 0) + self.fg_color = (255, 255, 255) + self.offset = 0 + self.period = 1 + self.previous_beat_time = 0 + + @staticmethod + def add_arguments(parser): + PygameHandler.add_arguments(parser) + parser.add_argument("--n", type=int, default=20, help="Number of tunnel parts") + parser.add_argument("--z0", type=float, default=0.05, help="Z-index (between 0 and 1) of the camera plane. Lower values increase FOV.") + + @classmethod + def from_args(cls, pipe, args): + return cls.from_keys(pipe, args, [], PygameHandler.BASE_KWARG_KEYS + ["n", "z0"]) + + def setup(self): + PygameHandler.setup(self, "BeatViewer: Tunnel") + + def handle_beat(self): + self.previous_beat_time = time.time() + + def handle_bpm(self, bpm): + self.period = 60 / bpm + + def update(self): + now = time.time() + self.offset = (now - self.previous_beat_time) / self.period / self.n + if self.offset > 1 / self.n: + self.previous_beat_time = now + self.offset -= 1 / self.n + self.window.fill(self.bg_color) + for i in range(self.n, 0, -1): + z = i / self.n - self.offset + if z <= 0: + continue + points = [] + for x, y in [(-.5, -.5), (-.5, .5), (.5, .5), (.5, -.5)]: + points.append([ + (x * self.z0 / z + .5) * self.width, + (y * self.z0 / z + .5) * self.height + ]) + if i == self.n: + pygame.draw.aaline(self.window, self.fg_color, (0, 0), points[0]) + pygame.draw.aaline(self.window, self.fg_color, (0, self.height), points[1]) + pygame.draw.aaline(self.window, self.fg_color, (self.width, self.height), points[2]) + pygame.draw.aaline(self.window, self.fg_color, (self.width, 0), points[3]) + pygame.draw.aalines(self.window, self.fg_color, True, points) \ No newline at end of file diff --git a/beatviewer/handlers/warp.py b/beatviewer/handlers/warp.py new file mode 100644 index 0000000..889b317 --- /dev/null +++ b/beatviewer/handlers/warp.py @@ -0,0 +1,229 @@ +import json +import os +import random +import re +import time + +from ..beat_handler_process import BeatHandlerProcess +from ..video.video_player import VideoPlayer +from ..video.video_stream import VideoStream + + +TIMING_FUNCTION_LINEAR = 0 +TIMING_FUNCTION_POWER = 1 +TIMING_FUNCTION_BEZIER = 2 + + +def cubic_bezier(x1, y1, x2, y2, p, tol=.01): + t = None + left = 0 + right = 1 + while True: + t = .5 * (left + right) + x = 3 * x1 * t * ((1 - t) ** 2) + 3 * x2 * (t ** 2) * (1 - t) + t ** 3 + if abs(x - p) < tol: + break + if x > p: + right = t + else: + left = t + return 3 * y1 * t * ((1 - t) ** 2) + 3 * y2 * (t ** 2) * (1 - t) + t ** 3 + + +def buffered_cubic_bezier(x1, y1, x2, y2, tol=.001, step=.001): + buffer = {0: 0, round(1 / step): 1} + p = step + while p < 1: + buffer[round(p / step)] = cubic_bezier(x1, y1, x2, y2, p, tol=tol) + p += step + def aux(q): + return buffer.get(round(q / step), 0) + return aux + + +def parse_timing_argument(string): + if string is None: + return TIMING_FUNCTION_LINEAR, [] + match = re.match(r"^([\w\-]+)(?:\((.+)\))?$", string) + if match.group(1) is None or string == "linear": + return TIMING_FUNCTION_LINEAR, [] + if match.group(1) == "ease-in": + return TIMING_FUNCTION_BEZIER, (0.42, 0, 1, 1) + elif match.group(1) == "ease-out": + return TIMING_FUNCTION_BEZIER, (0, 0, 0.58, 1) + elif match.group(1) == "ease-weak": + return TIMING_FUNCTION_BEZIER, (0.3, 0, 0.7, 1) + elif match.group(1) == "ease-medium": + return TIMING_FUNCTION_BEZIER, (0.42, 0, 0.58, 1) + elif match.group(1) == "ease-strong": + return TIMING_FUNCTION_BEZIER, (0.75, 0, 0.25, 1) + elif match.group(1) == "power": + return TIMING_FUNCTION_POWER, list(map(float, match.group(2).split(","))) + elif match.group(1) == "bezier": + return TIMING_FUNCTION_BEZIER, list(map(float, match.group(2).split(","))) + else: + raise ValueError("Incorrect timing function: '%s'" % string) + + +class Warp(BeatHandlerProcess): + + NAME = "warp" + + def __init__( + self, + pipe, + path, + fps=60, + rewind=0, + timing=None, + before=120, + after=120, + margin=120, + size=900, + virtual_cam=False, + prev_threshold=0.1, + next_threshold=0.1, + jumpcut=False, + ): + BeatHandlerProcess.__init__(self, pipe) + self.fps = fps + self.path = path + self.virtual_cam = virtual_cam + if self.virtual_cam: + self.output = VideoStream(path, size, self.fps) + else: + self.output = VideoPlayer(path, size) + self.checkpoints = None + self.rewind_probability = rewind + self.period = 1 + self.prev_beat_time = time.time() + self.next_beat_time = self.prev_beat_time + self.period + self.prev_video_frame = None + self.cur_video_frame_index = None + self.next_video_frame_in = 1 + self.next_checkpoint_index = 1 + self.direction = 1 + timing_argument = parse_timing_argument(timing) + self.timing_function = timing_argument[0] + self.timing_args = timing_argument[1] + self.bezier_curve = None + self.buffer_before = 0 if jumpcut else before + self.buffer_after = after + self.buffer_margin = margin + self.prev_beat_distance_threshold = prev_threshold + self.next_beat_distance_threshold = next_threshold + self.jumpcut = jumpcut + self.last_loop = 0 + + @staticmethod + def add_arguments(parser): + parser.add_argument("video_path", type=str, help="Path to the video file") + parser.add_argument("--fps", type=float, default=30, help="Framerate") + parser.add_argument("--rewind", type=float, default=0, help="Probability of going back in time at each checkpoint") + parser.add_argument("--timing", type=str, help="Timing function and arguments") + parser.add_argument("--before", type=int, default=120, help="Number of frames stored in the buffer before its cursor") + parser.add_argument("--after", type=int, default=120, help="Number of frames stored in the buffer after its cursor") + parser.add_argument("--margin", type=int, default=120, help="Number of frames above the default buffer size to trigger the cleanup") + parser.add_argument("--size", type=int, default=900, help="Length of the largest video edge") + parser.add_argument("--virtual-cam", action="store_true", help="Send video output to a virtual camera instead of a window") + parser.add_argument("--prev-threshold", type=float, default=0.1, help="Duration (in seconds) above which the timing is updated. Increase to reduce flickering.") + parser.add_argument("--next-threshold", type=float, default=0.1, help="Duration (in seconds) above which the timing is updated. Increase to reduce flickering.") + parser.add_argument("--jumpcut", action="store_true", help="Jump to a random checkpoint when a beat occurs instead of warped playback") + + @classmethod + def from_args(cls, pipe, args): + return cls.from_keys( + pipe, + args, + ["video_path"], + ["fps", "rewind", "timing", "before", "after", "margin", "size", + "virtual_cam", "prev_threshold","next_threshold", "jumpcut"]) + + def setup(self): + self.output.setup({ + "before": self.buffer_before, + "after": self.buffer_after, + "margin": self.buffer_margin + }) + data_path = os.path.splitext(self.path)[0] + ".json" + with open(data_path, "r") as file: + self.checkpoints = json.load(file).get("checkpoints") + self.prev_video_frame = self.checkpoints[0] + if self.timing_function == TIMING_FUNCTION_BEZIER: + self.bezier_curve = buffered_cubic_bezier(*self.timing_args) + + def handle_beat(self): + t = time.time() + distance_prev = abs(self.prev_beat_time - t) + distance_next = abs(self.next_beat_time - t) + if distance_next < distance_prev and distance_next > self.next_beat_distance_threshold: + self.prev_beat_time = t - self.period + self.next_beat_time = t + elif distance_prev < distance_next and distance_prev > self.prev_beat_distance_threshold: + self.prev_beat_time = t + self.next_beat_time = t + self.period + + def handle_bpm(self, bpm): + self.period = 60 / bpm + self.next_beat_time = self.prev_beat_time + self.period + + def apply_timing_function(self, p): + if self.timing_function == TIMING_FUNCTION_LINEAR: + return p + elif self.timing_function == TIMING_FUNCTION_POWER: + return p ** self.timing_args[0] + elif self.timing_function == TIMING_FUNCTION_BEZIER: + return self.bezier_curve(p) + + def get_current_frame_index(self): + t = time.time() + p = max(0, min(1, (t - self.prev_beat_time) / (self.next_beat_time - self.prev_beat_time))) + if self.jumpcut: + frame_index = int(self.prev_video_frame + (t - self.prev_beat_time) * self.output.video.fps) % self.output.video.frame_count + else: + p = self.apply_timing_function(p) + frame_index = int(self.prev_video_frame + self.direction * p * self.next_video_frame_in) % self.output.video.frame_count + return t, p, frame_index + + def move_to_next_segment(self, t): + self.direction = 1 + if random.random() < self.rewind_probability and self.next_checkpoint_index > 0: + self.direction = -1 + self.prev_video_frame = self.checkpoints[self.next_checkpoint_index] + if self.jumpcut: + self.prev_video_frame = random.choice(self.checkpoints) + elif self.direction == 1: + self.next_checkpoint_index = (self.next_checkpoint_index + 1) % len(self.checkpoints) + next_video_frame = self.checkpoints[self.next_checkpoint_index] + if next_video_frame > self.prev_video_frame: + self.next_video_frame_in = next_video_frame - self.prev_video_frame + else: + self.next_video_frame_in = self.output.video.frame_count - self.prev_video_frame + next_video_frame + else: + self.next_checkpoint_index = (self.next_checkpoint_index - 1 + len(self.checkpoints)) % len(self.checkpoints) + next_video_frame = self.checkpoints[self.next_checkpoint_index] + if next_video_frame > self.prev_video_frame: + self.next_video_frame_in = self.prev_video_frame + self.output.video.frame_count - next_video_frame + else: + self.next_video_frame_in = self.prev_video_frame - next_video_frame + self.prev_beat_time = t + self.next_beat_time = t + self.period + + def loop(self): + now = time.time() + if now - self.last_loop <= 1 / self.fps: + return + self.last_loop = now + t, p, frame_index = self.get_current_frame_index() + if not self.virtual_cam: + self.output.check_events(t) + self.running &= self.output.running + if frame_index != self.output.cursor: + self.output.cursor = frame_index + self.output.blit_current_frame(update=True) + if abs(p - 1) < .001: + self.move_to_next_segment(t) + + def close(self): + self.output.close() + BeatHandlerProcess.close(self) diff --git a/beatviewer/handlers/waves.py b/beatviewer/handlers/waves.py new file mode 100644 index 0000000..009dc44 --- /dev/null +++ b/beatviewer/handlers/waves.py @@ -0,0 +1,102 @@ +""" +Inspiration: https://wifflegif.com/gifs/424480-monochrome-infinite-gif +""" + +import math +import time + +import pygame + +from .pygame_handler import PygameHandler + + +BACKROUND = (225, 225, 228) +FOREGROUND = (0, 0, 0) + + +def gaussian(mu, sigma): + return lambda t: math.exp(-.5 * ((t - mu) / sigma) ** 2) + + +class Waves(PygameHandler): + + NAME = "waves" + + def __init__( + self, + pipe, + width=400, + height=400, + fullscreen=False, + fps=60, + line_count=20, + line_offset=0.05, + dot_count=50, + dot_offset=0.01, + sigma=0.1, + amplitude=10, + offset=0, + abs_distance=False, + buffer_size=20, + ): + PygameHandler.__init__(self, pipe, width, height, fullscreen, fps) + self.line_count = line_count + self.line_offset_seconds = line_offset + self.dot_count = dot_count + self.dot_offset_seconds = dot_offset + self.gaussians_buffer_size = buffer_size + self.gaussian_sigma = sigma + self.gaussian_amplitude = amplitude + self.gaussian_offset_seconds = offset + self.abs_distance = abs_distance + self.gaussians = [] + self.t0 = None + + @staticmethod + def add_arguments(parser): + PygameHandler.add_arguments(parser) + parser.add_argument("--line-count", type=int, default=20, help="Number of lines") + parser.add_argument("--line-offset", type=float, default=0.001, help="Time difference between two lines, in seconds") + parser.add_argument("--dot-count", type=int, default=50, help="Number of dots per line") + parser.add_argument("--dot-offset", type=float, default=0.0007, help="Time difference between two dots, in seconds") + parser.add_argument("--amplitude", type=float, default=100, help="Gaussian perturbation amplitude, in pixels") + parser.add_argument("--sigma", type=float, default=0.1, help="Gaussian perturbation width") + parser.add_argument("--offset", type=float, default=0, help="Static perturbation offset, in seconds") + parser.add_argument("--abs-distance", action="store_true", help="Use absolute distance instead of Euclidean norm for spacing lines and dots") + parser.add_argument("--buffer-size", type=int, default=20, help="Gaussian buffer size") + + @classmethod + def from_args(cls, pipe, args): + return cls.from_keys( + pipe, args, [], PygameHandler.BASE_KWARG_KEYS + ["line_count", "line_offset", "dot_count", "dot_offset", "amplitude", "sigma", "offset", "abs_distance", "buffer_size"]) + + def setup(self): + PygameHandler.setup(self, "BeatViewer: Waves") + self.t0 = time.time() + + def handle_beat(self): + self.gaussians.append(gaussian(time.time(), self.gaussian_sigma)) + if len(self.gaussians) > self.gaussians_buffer_size: + self.gaussians.pop(0) + + def update(self): + self.window.fill(BACKROUND) + now = time.time() + for i in range(self.line_count): + line_x = (i + .2) * self.width / self.line_count + dots = [] + dist_i = i - (self.line_count - 1) / 2 + for j in range(self.dot_count): + dist_j = j - (self.dot_count - 1) / 2 + dot_t = now + if self.abs_distance: + dot_t -= abs(self.line_offset_seconds * dist_i) + abs(self.dot_offset_seconds * dist_j) + else: + dot_t -= (self.line_offset_seconds * dist_i**2 + self.dot_offset_seconds * dist_j**2) ** .5 + dot_x = 0 + for g in self.gaussians: + dot_x += g(dot_t) + dot_x = dot_x * self.gaussian_amplitude + line_x + dot_y = (j + .5) * self.height / self.dot_count + dots.append((dot_x, dot_y)) + pygame.draw.aalines(self.window, FOREGROUND, False, dots) diff --git a/beatviewer/handlers/web_handler.py b/beatviewer/handlers/web_handler.py new file mode 100644 index 0000000..32d9384 --- /dev/null +++ b/beatviewer/handlers/web_handler.py @@ -0,0 +1,91 @@ +import http.server +import os +import socketserver +import threading +import time +import webbrowser + +from .socket import Socket + + +class AsyncWebServer(threading.Thread): + + def __init__(self, port, document_root, base_url, delay, socket_uri): + self.port = port + self.document_root = os.path.realpath(document_root) + self.base_url = base_url + self.delay = delay + self.socket_uri = socket_uri + threading.Thread.__init__(self, daemon=True) + + def run(self): + directory = self.document_root + class Handler(http.server.SimpleHTTPRequestHandler): + def __init__(self, *args, **kwargs): + super().__init__(*args, directory=directory, **kwargs) + time.sleep(self.delay) + with socketserver.TCPServer(("", self.port), Handler) as httpd: + url = f"http://localhost:{self.port}{self.base_url}?uri={self.socket_uri}" + webbrowser.open(url, new=2) + print(f"Web server is starting. Browser should open automatically. If not, you may access it here:\n\t{url}") + httpd.serve_forever() + + +class WebHandler(Socket): + + NAME = None + SOCKET_HOST = "localhost" + SOCKET_PORT = 8765 + WEB_PORT = 8123 + DOCUMENT_ROOT = os.path.join(os.path.dirname(__file__), "..", "web") + URL = "/" + + def __init__( + self, + pipe, + mute_beats=False, + mute_onsets=False, + mute_bpm=False): + Socket.__init__( + self, + pipe, + host=self.SOCKET_HOST, + port=self.SOCKET_PORT, + web=True, + mute_beats=mute_beats, + mute_onsets=mute_onsets, + mute_bpm=mute_bpm) + self.web_server = None + + @staticmethod + def add_arguments(parser): + parser.add_argument("--mute-beats", action="store_true", help="Do not handle beats") + parser.add_argument("--mute-onsets", action="store_true", help="Do not handle onsets") + parser.add_argument("--mute-bpm", action="store_true", help="Do not handle BPM") + + @classmethod + def from_args(cls, pipe, args): + return cls.from_keys(pipe, args, [], ["mute_beats", "mute_onsets", "mute_bpm"]) + + def setup(self): + self.web_server = AsyncWebServer( + self.WEB_PORT, + self.DOCUMENT_ROOT, + self.URL, + 1, + f"ws://{self.SOCKET_HOST}:{self.SOCKET_PORT}" + ) + self.web_server.start() + Socket.setup(self) + + +class Fireworks(WebHandler): + + NAME = "fireworks" + URL = "/fireworks.html" + + +class Fluid(WebHandler): + + NAME = "fluid" + URL = "/fluid.html" diff --git a/beatviewer/pipelines/__init__.py b/beatviewer/pipelines/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/beatviewer/pipelines/audio_stream_pipeline.py b/beatviewer/pipelines/audio_stream_pipeline.py new file mode 100644 index 0000000..a2d7e96 --- /dev/null +++ b/beatviewer/pipelines/audio_stream_pipeline.py @@ -0,0 +1,37 @@ +import logging + +import numpy +import scipy.fftpack + + +class AudioStreamPipeline: + + def __init__(self, config, audio_source): + logging.info("Creating audio stream pipeline") + self.config = config + self.audio_source = audio_source + self.sampling_rate = audio_source.sampling_rate + self.audio_window = None + self.previous_fft = None + self.flux = None + + def setup(self): + logging.info("Setting up audio stream pipeline") + self.audio_source.setup() + self.audio_window = numpy.zeros(self.config.audio_window_size) + self.previous_fft = numpy.zeros(self.config.audio_window_size) + + def update(self): + logging.debug("Updating audio stream pipeline") + self.audio_source.update_window(self.audio_window) + fft = numpy.abs(scipy.fftpack.fft(self.audio_window)) / self.sampling_rate + g = self.config.compression_gamma + if g != 0: + fft = numpy.log10(1 + g * fft) / numpy.log10(1 + g) + fft[fft < self.config.noise_cancellation_threshold] = 0 + self.flux = numpy.sum(numpy.maximum(fft - self.previous_fft, 0)) + self.previous_fft = fft + + def close(self): + logging.info("Closing audio stream pipeline") + self.audio_source.close() \ No newline at end of file diff --git a/beatviewer/pipelines/beat_tracking_pipeline.py b/beatviewer/pipelines/beat_tracking_pipeline.py new file mode 100644 index 0000000..4d84506 --- /dev/null +++ b/beatviewer/pipelines/beat_tracking_pipeline.py @@ -0,0 +1,149 @@ +import logging + +import numpy + + +def create_hamming_window(size, a0=25/46): + arr = numpy.zeros(size) + for k in range(size): + arr[k] = a0 - (1 - a0) * numpy.cos(2 * numpy.pi * k / size) + return arr + + +class BeatTrackingPipeline: + + MODE_REGULAR = 0 + MODE_TEMPO_LOCKED = 1 + + def __init__(self, config): + logging.info("Creating beat tracking pipeline") + self.config = config + self.mode = self.MODE_REGULAR + self.flux_buffer = None + self.oss_buffer = None + self.oss_buffer_size = 0 + self.oss_mean = 0 + self.oss_threshold = 0 + self.was_below_threshold = False + self.hamming_window = None + self.tempo_lag = 100 + self.phi_max = 0 + self.cbss_buffer = None + self.bps_buffer = None + self.beat_cooldown = 0 + self.running = True + self.beat_flag = False + self.onset_flag = False + self.frame_index = -1 + + def setup(self): + """Instantiate object attributes. + """ + logging.info("Setting up beat tracking pipeline") + self.flux_buffer = numpy.zeros((self.config.hamming_window_size)) + self.oss_buffer = [] + self.oss_buffer_size = 0 + self.hamming_window = create_hamming_window(self.config.hamming_window_size) + self.cbss_buffer = [0] * self.config.cbss_buffer_size + self.bps_buffer = [0] * self.config.bps_buffer_size + + def enqueue_flux(self, flux): + logging.debug("Enqueuing flux value %f", flux) + self.frame_index += 1 + self.flux_buffer[:self.config.hamming_window_size - 1] = self.flux_buffer[1:] + self.flux_buffer[-1] = flux + self.update_oss() + self.update_cbss() + self.update_phi_max() + self.update_bps() + self.update_beat() + + def set_tempo_lag(self, tempo_lag): + """Set the tempo_lag attribute + """ + if self.mode != self.MODE_TEMPO_LOCKED: + self.tempo_lag = tempo_lag + + def update_oss(self): + """Compute the next OSS value and store it into a buffer. + Return whether there was an onset. + """ + oss = numpy.sum(numpy.multiply(self.flux_buffer, self.hamming_window)) + if self.oss_buffer_size == max(self.config.oss_window_size, self.config.oss_buffer_size): + self.oss_buffer.pop(0) + self.oss_buffer_size -= 1 + self.oss_buffer.append(oss) + self.oss_buffer_size += 1 + self.oss_mean = numpy.mean(self.oss_buffer[-self.config.oss_buffer_size:]) + oss_std = numpy.sqrt(numpy.var(self.oss_buffer[-self.config.oss_buffer_size:])) + self.oss_threshold = max( + self.oss_mean + self.config.onset_threshold * oss_std, + self.config.onset_threshold_min + ) + self.onset_flag = False + if oss < self.oss_threshold: + self.was_below_threshold = True + logging.debug("Detected onset") + elif self.was_below_threshold: + self.was_below_threshold = False + self.onset_flag = True + return self.onset_flag + + def update_cbss(self): + """Compute the next CBSS value and store it into a buffer. + """ + self.cbss_buffer.pop(0) + self.cbss_buffer.append(0) + n = self.config.cbss_buffer_size - 1 + phi = 0 + for v in range(-2 * self.tempo_lag, -self.tempo_lag // 2): + if n + v < 0: + continue + gaussian_weight = numpy.exp(-.5 * (self.config.cbss_eta * numpy.power(numpy.log(-v/self.tempo_lag), 2))) + phi = max(phi, gaussian_weight * self.cbss_buffer[n + v]) + if self.mode == self.MODE_TEMPO_LOCKED: + self.cbss_buffer[n] = phi + else: + self.cbss_buffer[n] = (1 - self.config.cbss_alpha) * self.oss_buffer[-1] + self.config.cbss_alpha * phi + + def update_phi_max(self): + """Compute the phase estimation. + """ + phi_max, phi_max_value = None, None + n = self.config.cbss_buffer_size - 1 + for phi in range(self.tempo_lag): + phi_value = 0 + for i in range(4): + if n - phi - i * self.tempo_lag < 0: + continue + phi_value += self.cbss_buffer[n - phi - i * self.tempo_lag] + if phi_max is None or phi_value > phi_max_value: + phi_max, phi_max_value = phi, phi_value + self.phi_max = phi_max + + def update_bps(self): + """Update the BPS buffer. + """ + self.bps_buffer.pop(0) + self.bps_buffer.append(0) + epsilon = self.config.bps_epsilon_o + self.config.bps_epsilon_r + tt = [ + (i % self.tempo_lag) - (self.tempo_lag - self.phi_max - epsilon) + for i in range(self.config.bps_buffer_size) + ] + pmi = numpy.exp(-numpy.power(tt, 2) / self.config.bps_gaussian_width) + for i in range(self.config.bps_buffer_size): + self.bps_buffer[i] += pmi[i] + + def update_beat(self): + """Take the decision of the presence of a beat. + """ + self.beat_flag = False + if self.beat_cooldown > 0: + self.beat_cooldown -= 1 + return False + self.beat_flag = self.bps_buffer[self.config.bps_epsilon_t] == max(self.bps_buffer) + if self.beat_flag: + self.beat_cooldown = int(self.config.bps_cooldown_ratio * self.tempo_lag) + logging.debug("Detected beat") + return self.beat_flag \ No newline at end of file diff --git a/beatviewer/pipelines/pipeline.py b/beatviewer/pipelines/pipeline.py new file mode 100644 index 0000000..019aae8 --- /dev/null +++ b/beatviewer/pipelines/pipeline.py @@ -0,0 +1,50 @@ +import logging + +from .audio_stream_pipeline import AudioStreamPipeline +from .beat_tracking_pipeline import BeatTrackingPipeline +from .tempo_estimation_pipeline import TempoEstimationPipepline + + +class Pipeline(AudioStreamPipeline, BeatTrackingPipeline, TempoEstimationPipepline): + + def __init__(self, config, audio_source): + logging.info("Creating pipeline") + AudioStreamPipeline.__init__(self, config, audio_source) + BeatTrackingPipeline.__init__(self, config) + TempoEstimationPipepline.__init__(self, audio_source.sampling_rate / config.audio_hop_size, config) + self.oss_buffer_counter = None + self.bpm_flag = False + self.active = True + + def setup(self): + logging.info("Setting up pipeline") + AudioStreamPipeline.setup(self) + BeatTrackingPipeline.setup(self) + TempoEstimationPipepline.setup(self) + self.oss_buffer_counter = 0 + + def update(self): + logging.debug("Updating pipeline") + AudioStreamPipeline.update(self) + self.active = self.audio_source.active + BeatTrackingPipeline.enqueue_flux(self, self.flux) + self.oss_buffer_counter += 1 + self.bpm_flag = False + if self.oss_buffer_counter >= self.config.oss_hop_size and self.oss_buffer_size == self.config.oss_window_size: + self.oss_buffer_counter = 0 + TempoEstimationPipepline.update(self) + if self.scaled_tempo_lag is None: + return + new_tempo_lag = int(self.scaled_tempo_lag) + if new_tempo_lag != self.tempo_lag: + self.tempo_lag = new_tempo_lag + self.bpm_flag = True + logging.debug("New tempo lag: %d", self.tempo_lag) + + def close(self): + logging.info("Closing pipeline") + AudioStreamPipeline.close(self) + + @property + def bpm(self): + return 60 * self.oss_sampling_rate / self.tempo_lag \ No newline at end of file diff --git a/beatviewer/pipelines/tempo_estimation_pipeline.py b/beatviewer/pipelines/tempo_estimation_pipeline.py new file mode 100644 index 0000000..d687e50 --- /dev/null +++ b/beatviewer/pipelines/tempo_estimation_pipeline.py @@ -0,0 +1,121 @@ +import logging + +import numpy +import scipy.signal +import scipy.fftpack + + +def create_pulse_trains(t_min, t_max): + pulse_trains = {} + for candidate_tempo in range(t_min, t_max + 1): + for phi in range(candidate_tempo): + pulse_trains[candidate_tempo, phi] = {} + for pulse_index, pulse_weight in zip([1, 1.5, 2], [1, .5, .5]): + for beat_index in [0, 1, 2, 3]: + i = int(phi + pulse_index * beat_index * candidate_tempo) + pulse_trains[candidate_tempo, phi].setdefault(i, 0) + pulse_trains[candidate_tempo, phi][i] += pulse_weight + return pulse_trains + + +class TempoEstimationPipepline: + + def __init__(self, oss_sampling_rate, config): + logging.info("Creating tempo estimation pipeline") + self.oss_sampling_rate = oss_sampling_rate + self.config = config + self.t_min = None + self.t_max = None + self.oss_buffer = None + self.oss_buffer_size = None + self.eac = None + self.pulse_trains = None + self.instant_tempo_lag = None + self.accumulator = None + self.accumulated_tempo_lag = None + self.scaled_tempo_lag = None + + def setup(self): + logging.info("Setting up tempo estimation pipeline") + self.t_min = int(60 * self.oss_sampling_rate / self.config.max_bpm_detection) + self.t_max = int(60 * self.oss_sampling_rate / self.config.min_bpm_detection) + self.oss_buffer = [] + self.oss_buffer_size = 0 + self.pulse_trains = create_pulse_trains(self.t_min, self.t_max) + self.accumulator = numpy.zeros(self.t_max - self.t_min + 1) + + def enqueue_oss(self, oss): + """Enqueue an OSS to the tempo estimator window. If the window reaches + the size specified in config.oss_window_size, it triggers an update and + returns True. Otherwise it returns False. + """ + self.oss_buffer.append(oss) + self.oss_buffer_size += 1 + if self.oss_buffer_size == self.config.oss_window_size: + self.update() + del self.oss_buffer[:self.config.oss_hop_size] + self.oss_buffer_size -= self.config.oss_hop_size + return True + return False + + def update(self): + logging.debug("Updating tempo estimation pipeline") + self.update_eac() + self.update_instant_tempo_lag() + self.update_accumulator() + + def update_eac(self): + corr = numpy.abs(scipy.fftpack.ifft(numpy.power( + numpy.abs(scipy.fftpack.fft(self.oss_buffer)), + self.config.frequency_domain_compression))) + self.eac = numpy.copy(corr) + for t in range(self.config.oss_window_size // 4): + self.eac[t] += corr[2 * t] + corr[4 * t] + for t in range(self.config.oss_window_size // 4, self.config.oss_window_size // 2): + self.eac[t] += corr[2 * t] + + def update_instant_tempo_lag(self): + peaks = scipy.signal.find_peaks(self.eac[self.t_min:self.t_max + 1])[0] + self.t_min + if len(peaks) == 0: + return + tempo_candidates = min(len(peaks), self.config.tempo_candidates) + top_peaks = numpy.argpartition(self.eac[peaks], -tempo_candidates)[-tempo_candidates:] + scores_variance = numpy.zeros(tempo_candidates) + scores_variance_sum = 0 + scores_maximum = numpy.zeros(tempo_candidates) + scores_maximum_sum = 0 + for j, candidate_tempo in enumerate(peaks[top_peaks]): + pulse_train_correlation = numpy.zeros(candidate_tempo) + for phi in range(candidate_tempo): + for i, v in self.pulse_trains[candidate_tempo, phi].items(): + if i >= self.config.oss_window_size: + continue + pulse_train_correlation[phi] += v * self.oss_buffer[i] + variance = numpy.var(pulse_train_correlation) + scores_variance[j] = variance + scores_variance_sum += variance + maximum = numpy.max(pulse_train_correlation) + scores_maximum[j] = maximum + scores_maximum_sum += maximum + if scores_variance_sum == 0: + scores_variance_sum = 1 + if scores_maximum_sum == 0: + scores_maximum_sum = 1 + scores = scores_variance / scores_variance_sum + scores_maximum / scores_maximum_sum + j_max = numpy.argmax(scores) + self.instant_tempo_lag = peaks[top_peaks][j_max] + + def update_accumulator(self): + if self.instant_tempo_lag is None: + return + t = list(range(self.t_min, self.t_max + 1)) + self.accumulator *= self.config.tempo_accumulator_decay + s = self.config.tempo_accumulator_gaussian_width + self.accumulator += 1 / (s * numpy.sqrt(2 * numpy.pi)) * numpy.exp(-.5 * numpy.power((t - self.instant_tempo_lag) / s, 2)) + self.accumulated_tempo_lag = numpy.argmax(self.accumulator) + self.t_min + bpm = 60 * self.oss_sampling_rate / self.accumulated_tempo_lag + while bpm <= self.config.min_bpm_rescaled: + bpm *= 2 + while bpm >= self.config.max_bpm_rescaled: + bpm *= .5 + self.scaled_tempo_lag = 60 * self.oss_sampling_rate / bpm \ No newline at end of file diff --git a/beatviewer/tools/__init__.py b/beatviewer/tools/__init__.py new file mode 100644 index 0000000..fecd9da --- /dev/null +++ b/beatviewer/tools/__init__.py @@ -0,0 +1,9 @@ +from .annotator import Annotator +from .directogram import Directogram +from .dummy import Dummy + +TOOL_LIST = [ + Annotator, + Directogram, + Dummy +] \ No newline at end of file diff --git a/beatviewer/tools/annotator.py b/beatviewer/tools/annotator.py new file mode 100644 index 0000000..8aad609 --- /dev/null +++ b/beatviewer/tools/annotator.py @@ -0,0 +1,269 @@ +import json +import os + +import pygame + +from ..video.video_player import VideoPlayer +from .tool import Tool + + +WHITE = (255, 255, 255) +BLACK = (0, 0, 0) +RED = (255, 0, 0) + + +class Annotator(Tool, VideoPlayer): + + NAME = "annotator" + + MONITORED_KEYS = [ + pygame.K_RIGHT, + pygame.K_LEFT, + pygame.K_SPACE, + pygame.K_LALT, + pygame.K_LSHIFT, + pygame.K_RSHIFT, + pygame.K_LCTRL + ] + + def __init__( + self, + path, + size=900, + buffer_before=30, + buffer_after=30, + buffer_margin=120 + ): + pygame.init() + Tool.__init__(self) + VideoPlayer.__init__(self, path, size=size, noframe=False) + self.time_of_previous_checkpoint = None + self.checkpoints = set() + self.pressed = set() + self.font16 = pygame.font.SysFont("Consolas", 16) + self.prev_checkpoint = None + self.prev_checkpoint_distance = None + self.next_checkpoint = None + self.next_checkpoint_distance = None + self.playback_period = 60 / 100 + self.playback_warping_power = 1.5 + self.buffer_before = buffer_before + self.buffer_after = buffer_after + self.buffer_margin = buffer_margin + self.unused_data = {} + + @staticmethod + def add_arguments(parser): + parser.add_argument("path", type=str, help="Path to a video file") + parser.add_argument("-s", "--size", type=int, default=900, help="Maximum size of the window") + parser.add_argument("-b", "--buffer-before", type=int, default=30, help="Number of frames stored in the buffer before its cursor") + parser.add_argument("-a", "--buffer-after", type=int, default=30, help="Number of frames stored in the buffer after its cursor") + parser.add_argument("-m", "--buffer-margin", type=int, default=120, help="Number of frames above the default buffer size to trigger the cleanup") + + @classmethod + def from_args(cls, args): + return cls.from_keys(args, ["path"], ["size", "buffer_before", "buffer_after", "buffer_margin"]) + + def setup(self): + self.load() + VideoPlayer.setup(self, { + "before": self.buffer_before, + "after": self.buffer_after, + "margin": self.buffer_margin + }) + self.update_surrounding_checkpoints() + self.time_of_previous_checkpoint = 0 + + def set_cursor(self, i): + self.cursor = i % self.video.frame_count + self.update_surrounding_checkpoints() + self.update_display() + + def goto_prev(self): + self.set_cursor(self.cursor - 1) + + def goto_next(self): + self.set_cursor(self.cursor + 1) + + def goto_prev_checkpoint(self): + if self.prev_checkpoint is not None: + self.set_cursor(self.prev_checkpoint) + + def goto_next_checkpoint(self): + if self.next_checkpoint is not None: + self.set_cursor(self.next_checkpoint) + + def goto_start(self): + self.set_cursor(0) + + def goto_end(self): + self.set_cursor(self.video.frame_count - 1) + + def toggle_checkpoint(self): + if self.cursor in self.checkpoints: + self.checkpoints.remove(self.cursor) + else: + self.checkpoints.add(self.cursor) + self.update_display() + + def update_surrounding_checkpoints(self): + self.prev_checkpoint = None + self.prev_checkpoint_distance = None + self.next_checkpoint = None + self.next_checkpoint_distance = None + if not self.checkpoints: + return + for checkpoint in sorted(self.checkpoints): + if checkpoint < self.cursor: + self.prev_checkpoint = checkpoint + self.prev_checkpoint_distance = self.cursor - checkpoint + elif checkpoint > self.cursor: + self.next_checkpoint = checkpoint + self.next_checkpoint_distance = checkpoint - self.cursor + break + if self.prev_checkpoint is None and self.checkpoints: + self.prev_checkpoint = max(self.checkpoints) + self.prev_checkpoint_distance = self.cursor + self.video.frame_count - self.prev_checkpoint + if self.next_checkpoint is None and self.checkpoints: + self.next_checkpoint = min(self.checkpoints) + self.next_checkpoint_distance = self.video.frame_count - self.cursor + self.next_checkpoint + + def draw_hud(self): + y = 8 + + text = self.font16.render(f"#{self.cursor}", True, WHITE, BLACK) + self.window.blit(text, (8, y)) + y += text.get_height() + 1 + + t = self.cursor / self.video.fps + text = self.font16.render("%02d:%02d:%03d" % (t / 60, t % 60, (t * 1e3) % 1e3), True, WHITE, BLACK) + self.window.blit(text, (8, y)) + y += text.get_height() + 1 + + if self.prev_checkpoint is None: + text = self.font16.render(f"prev: -", True, WHITE, BLACK) + else: + text = self.font16.render(f"prev: {self.prev_checkpoint} (-{self.prev_checkpoint_distance})", True, WHITE, BLACK) + self.window.blit(text, (8, y)) + y += text.get_height() + 1 + + if self.next_checkpoint is None: + text = self.font16.render(f"next: -", True, WHITE, BLACK) + else: + text = self.font16.render(f"next: {self.next_checkpoint} (+{self.next_checkpoint_distance})", True, WHITE, BLACK) + self.window.blit(text, (8, y)) + y += text.get_height() + 1 + + pygame.draw.rect(self.window, BLACK, pygame.Rect(8, self.height - 24, self.width - 16, 16)) + pygame.draw.line(self.window, WHITE, (16, self.height - 16), (self.width - 16, self.height - 16)) + x = int((self.cursor / (self.video.frame_count - 1)) * (self.width - 32) + 16) + pygame.draw.line(self.window, WHITE, (x, self.height - 16 + 8), (x, self.height - 16 - 8)) + for checkpoint in self.checkpoints: + x = int((checkpoint / (self.video.frame_count - 1)) * (self.width - 32) + 16) + pygame.draw.line(self.window, RED, (x, self.height - 16 + 4), (x, self.height - 16 - 4)) + + if self.cursor in self.checkpoints: + pygame.draw.circle(self.window, RED, (self.width - 75, 75), 60) + + def check_events(self, t): + for event in pygame.event.get(): + if event.type == pygame.QUIT: + self.running = False + break + elif event.type == pygame.KEYDOWN: + if event.key == pygame.K_ESCAPE: + self.running = False + break + elif event.key == pygame.K_a and pygame.K_LCTRL in self.pressed: + self.goto_start() + elif event.key == pygame.K_e and pygame.K_LCTRL in self.pressed: + self.goto_end() + elif event.key == pygame.K_s and pygame.K_LCTRL in self.pressed: + self.save() + elif event.key == pygame.K_w and pygame.K_LCTRL in self.pressed: + self.running = False + break + elif event.key == pygame.K_RETURN: + self.toggle_checkpoint() + else: + for key in self.MONITORED_KEYS: + if event.key == key: + if key == pygame.K_SPACE: + self.time_of_previous_checkpoint = t + self.pressed.add(key) + break + elif event.type == pygame.KEYUP: + for key in self.MONITORED_KEYS: + if event.key == key and key in self.pressed: + self.pressed.remove(key) + break + + def update_display(self): + self.blit_current_frame(update=False) + self.draw_hud() + pygame.display.flip() + + def update_linear_playback(self, t): + self.time_of_previous_frame = t + if pygame.K_LEFT in self.pressed: + if pygame.K_LCTRL in self.pressed: + self.goto_prev_checkpoint() + else: + self.goto_prev() + if pygame.K_LSHIFT in self.pressed or pygame.K_RSHIFT in self.pressed: + self.pressed.remove(pygame.K_LEFT) + elif pygame.K_RIGHT in self.pressed: + if pygame.K_LCTRL in self.pressed: + self.goto_next_checkpoint() + else: + self.goto_next() + if pygame.K_LSHIFT in self.pressed or pygame.K_RSHIFT in self.pressed: + self.pressed.remove(pygame.K_RIGHT) + + def update_warped_playback(self, t): + prev_checkpoint = self.prev_checkpoint + prev_checkpoint_distance = self.prev_checkpoint_distance + if self.cursor in self.checkpoints: + prev_checkpoint = self.cursor + prev_checkpoint_distance = 0 + progress = (t - self.time_of_previous_checkpoint) / self.playback_period + progress = max(0, min(1, progress)) ** self.playback_warping_power + if progress >= 1: + self.time_of_previous_checkpoint = t + frame_distance = prev_checkpoint_distance + self.next_checkpoint_distance + self.set_cursor(int(prev_checkpoint + progress * frame_distance)) + + def update(self, t): + self.check_events(t) + if pygame.K_SPACE in self.pressed and self.checkpoints: + self.update_warped_playback(t) + return + if pygame.K_LALT not in self.pressed and t - self.time_of_previous_frame < 1 / self.video.fps: + return + self.update_linear_playback(t) + self.update_display() + + def load(self): + path = os.path.splitext(self.path)[0] + ".json" + if os.path.isfile(path): + with open(path, "r") as file: + self.unused_data = json.load(file) + self.checkpoints = set(self.unused_data["checkpoints"]) + del self.unused_data["checkpoints"] + + def save(self): + path = os.path.splitext(self.path)[0] + ".json" + with open(path, "w") as file: + data = { **self.unused_data } + data.update({ + "path": self.path, + "frame_count": self.video.frame_count, + "frame_rate": self.video.fps, + "width": self.video.width, + "height": self.video.height, + "checkpoints": sorted(self.checkpoints), + }) + json.dump(data, file) + + def run(self): + VideoPlayer.run(self) \ No newline at end of file diff --git a/beatviewer/tools/directogram.py b/beatviewer/tools/directogram.py new file mode 100644 index 0000000..d0f4798 --- /dev/null +++ b/beatviewer/tools/directogram.py @@ -0,0 +1,134 @@ +import json +import math +import os + +import cv2 +import numpy +import tqdm + +from ..video.video_reader import VideoReader +from .tool import Tool + + +class Directogram(Tool, VideoReader): + + NAME = "directogram" + + def __init__(self, path, deadzone=0.05, bins=128, average_period=1, maximum_period=.15, sigma=2, skip_directogram=False): + Tool.__init__(self) + VideoReader.__init__(self, path) + self.last_frame = None + self.next_frame = None + self.directogram = [] + self.checkpoints = [] + self.deadzone = deadzone + self.bins = bins + self.average_period = average_period + self.maximum_period = maximum_period + self.sigma = sigma + self.skip_directogram = skip_directogram + + @staticmethod + def add_arguments(parser): + parser.add_argument("path", type=str, help="Path to the video file") + parser.add_argument("-s", "--skip-directogram", action="store_true", help="Set this flag to skip directogram computation, and reuse saved data") + parser.add_argument("--average-period", type=float, default=1.0, help="Length in seconds of the window for computating signal average and standard deviation") + parser.add_argument("--maximum-period", type=float, default=0.15, help="Length in seconds of the window for computatig signal local maxima") + parser.add_argument("--sigma", type=float, default=2.0, help="Threshold to detect a checkpoint, as a number of std above the mean") + + @classmethod + def from_args(cls, args): + return cls.from_keys(args, ["path"], ["skip_directogram", "average_period", "maximum_period", "sigma"]) + + def save(self): + path = os.path.splitext(self.path)[0] + ".json" + with open(path, "w") as file: + json.dump({ + "path": self.path, + "frame_count": self.frame_count, + "frame_rate": self.fps, + "width": self.width, + "height": self.height, + "checkpoints": sorted(self.checkpoints), + "directogram": self.directogram.tolist() + }, file) + + def load(self): + path = os.path.splitext(self.path)[0] + ".json" + if not os.path.isfile(path): + return + with open(path, "r") as file: + data = json.load(file) + self.checkpoints = data.get("checkpoints") + self.directogram = numpy.array(data["directogram"]) if "directogram" in data else None + + def increment_cursor(self): + self.last_frame = self.next_frame + self.next_frame = numpy.mean(self.read_frame(), axis=2) + + def compute_optical_flow(self): + flow = cv2.calcOpticalFlowFarneback( + prev=self.last_frame, + next=self.next_frame, + flow=None, + pyr_scale=0.5, + levels=int(math.log(float(min(self.next_frame.shape)), 2)) - 4, + winsize=15, + iterations=3, + poly_n=5, + poly_sigma=1.25, + flags=0, + ) + flow_angle = numpy.arctan2(flow[:,:,1], flow[:,:,0]) + numpy.pi + flow_radius = numpy.sqrt(numpy.sum(numpy.power(flow, 2), axis=2)) + starty = int(self.deadzone * self.next_frame.shape[0]) + endy = self.next_frame.shape[0] - starty + startx = int(self.deadzone * self.next_frame.shape[1]) + endx = self.next_frame.shape[1] - startx + return flow_angle[starty:endy, startx:endx], flow_radius[starty:endy, startx:endx] + + def compute_directogram(self): + self.cursor = 0 + self.next_frame = numpy.mean(self.read_frame(), axis=2) + histograms = [] + for _ in tqdm.tqdm(range(1, self.frame_count), unit="frame"): + self.increment_cursor() + flow_angle, flow_radius = self.compute_optical_flow() + histogram, _ = numpy.histogram( + flow_angle.ravel(), + bins=self.bins, + range=(0, 2 * numpy.pi), + weights=flow_radius.ravel(), + density=None + ) + histograms.append(histogram) + self.directogram = numpy.array(histograms) + # TODO: apply 3x3 median filter + return self.directogram + + def extract_checkpoints(self): + flux = numpy.sum( + numpy.maximum(0, self.directogram[1:,:] - self.directogram[:-1,:]), + axis=1) + flux /= numpy.max(flux) + local_mean_width = int(self.average_period * self.fps) + local_maxima_width = int(self.maximum_period * self.fps) + self.checkpoints = [] + for i in range(flux.shape[0]): + window = flux[max(0, int(i - local_mean_width / 2)):min(flux.shape[0], int(i + local_mean_width / 2) + 1)] + mean = numpy.mean(window) + std = numpy.sqrt(numpy.var(window)) + local_maximum = max(flux[ + max(0, int(i - local_maxima_width / 2)): + min(int(i + local_maxima_width / 2) + 1, flux.shape[0])]) + if flux[i] == local_maximum and flux[i] > mean + self.sigma * std: + self.checkpoints.append(i + 2) + return self.checkpoints + + def run(self): + self.open() + self.load() + if not self.skip_directogram: + self.compute_directogram() + self.extract_checkpoints() + self.save() diff --git a/beatviewer/tools/dummy.py b/beatviewer/tools/dummy.py new file mode 100644 index 0000000..9b8bce3 --- /dev/null +++ b/beatviewer/tools/dummy.py @@ -0,0 +1,97 @@ +import argparse +import keyboard +import multiprocessing +import os +import time + +from ..handlers import HANDLER_LIST +from ..beat_tracker_process import BeatTrackerProcess +from .tool import Tool + + +try: + import winsound + def beep(frequency, duration): + winsound.Beep(frequency, duration) +except ImportError: + def beep(frequency, duration): + os.system(f"beep -f { frequency } -l { duration }") + + +class Dummy(Tool): + + NAME = "dummy" + + def __init__(self, bpm, handler, onsets=False, keyboard_events=True, print_beat=False, beep_beat=False): + Tool.__init__(self) + self.bpm = bpm + self.handler = handler + self.onsets = onsets + self.keyboard_events = keyboard_events + self.print_beat = print_beat + self.beep_beat = beep_beat + self.args = None + + @staticmethod + def add_arguments(parser): + parser.add_argument("bpm", type=int) + parser.add_argument("-o", "--onsets", action="store_true", help="Send onsets every beat and half beat") + parser.add_argument("-p", "--print", action="store_true", help="Print beat to stdout", dest="print_beat") + parser.add_argument("-b", "--beep", action="store_true", help="Make noise when a beat occurs", dest="beep_beat") + parser.add_argument("-k", "--keyboard", action="store_true", help="Enable keyboard shortcuts", dest="keyboard_events") + handler_subparsers = parser.add_subparsers(dest="dummy_handler", required=True) + for cls in HANDLER_LIST: + subparser = handler_subparsers.add_parser(cls.NAME, formatter_class=argparse.ArgumentDefaultsHelpFormatter) + cls.add_arguments(subparser) + + @classmethod + def from_args(cls, args): + obj = cls.from_keys(args, ["bpm", "dummy_handler"], ["onsets", "print_beat", "beep_beat", "keyboard_events"]) + obj.args = args + return obj + + def run(self): + conn1, conn2 = multiprocessing.Pipe() + handler = None + for cls in HANDLER_LIST: + if cls.NAME == self.handler: + handler = cls.from_args(conn2, self.args) + break + handler.start() + try: + conn1.send((BeatTrackerProcess.FLAG_BPM, 0, 0, self.bpm)) + t0 = time.time() + t1 = t0 + t2 = t0 + while True: + t = time.time() + if self.keyboard_events: + if keyboard.is_pressed("pageup"): + self.bpm += 1 + conn1.send((BeatTrackerProcess.FLAG_BPM, 0, t - t0, self.bpm)) + print("BPM:", self.bpm) + elif keyboard.is_pressed("pagedown"): + self.bpm -= 1 + conn1.send((BeatTrackerProcess.FLAG_BPM, 0, t - t0, self.bpm)) + print("BPM:", self.bpm) + if t - t2 >= 30 / self.bpm: + time.sleep(.001) + if self.onsets and (t - t2 >= 30 / self.bpm or t - t1 >= 60 / self.bpm): + t2 = t + conn1.send((BeatTrackerProcess.FLAG_ONSET, 0, t - t0, None)) + if t - t1 >= 60 / self.bpm: + t1 = t + conn1.send((BeatTrackerProcess.FLAG_BEAT, 0, t - t0, None)) + if self.print_beat: + print("·", end="", flush=True) + if self.beep_beat: + beep(220, 70) + continue + if not handler.is_alive(): + break + time.sleep(.001) + except KeyboardInterrupt: + pass + finally: + handler.kill() + handler.join() diff --git a/beatviewer/tools/tool.py b/beatviewer/tools/tool.py new file mode 100644 index 0000000..23fa673 --- /dev/null +++ b/beatviewer/tools/tool.py @@ -0,0 +1,15 @@ +class Tool: + + def __init__(self): + pass + + @staticmethod + def add_arguments(parser): + pass + + @classmethod + def from_keys(cls, args, args_keys, kwargs_keys): + return cls(*[getattr(args, key) for key in args_keys], **{key: getattr(args, key) for key in kwargs_keys}) + + def run(self): + raise NotImplementedError \ No newline at end of file diff --git a/beatviewer/video/__init__.py b/beatviewer/video/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/beatviewer/video/video_buffer.py b/beatviewer/video/video_buffer.py new file mode 100644 index 0000000..5addb0c --- /dev/null +++ b/beatviewer/video/video_buffer.py @@ -0,0 +1,94 @@ +import threading +import time + +from .video_reader import VideoReader + + +def circular_interval(size, begin, end): + begin %= size + end %= size + if begin > end: + return set(range(begin, size)).union(range(end + 1)) + return set(range(begin, end + 1)) + + +class VideoBuffer(VideoReader, threading.Thread): + + def __init__(self, path, before=120, after=120, margin=120): + VideoReader.__init__(self, path) + threading.Thread.__init__(self, daemon=True) + self.before = before + self.after = after + self.size = self.before + self.after + 1 + self.buffer = {} + self.center = None + self.running = True + self.changed = False + self.lock_ready = threading.Lock() + self.lock_ready.acquire() + self.buffered_frames = 0 + self.margin = margin + + def setup(self): + self.open() + if self.size > self.frame_count: + if self.frame_count % 2 == 0: + self.before = self.frame_count // 2 - 1 + self.after = self.frame_count // 2 + else: + self.before = self.frame_count // 2 + self.after = self.frame_count // 2 + self.center = 0 + self.changed = True + self.update_buffer() + self.lock_ready.release() + + def wait_until_ready(self): + self.lock_ready.acquire() + + def interval(self): + return circular_interval(self.frame_count, self.center - self.before, self.center + self.after) + + def in_interval(self, i): + begin = (self.center - self.before) % self.frame_count + end = (self.center + self.after) % self.frame_count + if begin > end: + return i >= begin or i <= end + 1 + return i >= begin and i <= end + 1 + + def update_buffer(self): + self.changed = False + interval = self.interval() + if self.buffered_frames > self.size + self.margin: + indices_to_delete = set(self.buffer.keys()).difference(interval) + for i in indices_to_delete: + del self.buffer[i] + self.buffered_frames -= 1 + indices_to_add = interval.difference(self.buffer.keys()) + for i in sorted(indices_to_add): + # If a frame outside buffer range is accessed while the buffer is + # filling, we can abort the current operation: next frames will be + # useless. + if self.changed and not self.in_interval(self.center): + return + self.buffer[i] = self.read_frame(i) + self.buffered_frames += 1 + + def __getitem__(self, i): + self.changed = i != self.center + self.center = i + while not i in self.buffer and self.running: + time.sleep(.001) # TODO: consider using a lock? + return self.buffer[i] + + def terminate(self): + self.running = False + + def run(self): + self.setup() + while self.running: + if self.changed: + self.update_buffer() + else: + time.sleep(.001) + self.close() \ No newline at end of file diff --git a/beatviewer/video/video_output.py b/beatviewer/video/video_output.py new file mode 100644 index 0000000..ca65077 --- /dev/null +++ b/beatviewer/video/video_output.py @@ -0,0 +1,36 @@ +from .video_buffer import VideoBuffer + + +class VideoOutput: + + def __init__(self, path, size=900): + self.path = path + self.size = size + self.running = True + self.video = None + self.cursor = 0 + self.width = None + self.height = None + self.time_of_previous_frame = 0 + + def setup(self, buffer_kwargs={}): + self.video = VideoBuffer(self.path, **buffer_kwargs) + self.video.start() + self.video.wait_until_ready() + aspect = self.video.width / self.video.height + if aspect >= 1: + self.width = self.size + self.height = int(self.size / aspect) + else: + self.width = int(self.size * aspect) + self.height = self.size + + def increment(self): + self.cursor = (self.cursor + 1) % self.video.frame_count + + def blit_current_frame(self, update=True): + raise NotImplementedError + + def close(self): + self.video.terminate() + self.video.join() \ No newline at end of file diff --git a/beatviewer/video/video_player.py b/beatviewer/video/video_player.py new file mode 100644 index 0000000..bdfeb59 --- /dev/null +++ b/beatviewer/video/video_player.py @@ -0,0 +1,58 @@ +import os +import time + +import pygame + +from .video_reader import VideoReader +from .video_output import VideoOutput + + +class VideoPlayer(VideoOutput): + + def __init__(self, path, size=900, noframe=True): + VideoOutput.__init__(self, path, size) + self.window = None + self.noframe = noframe + + def setup(self, buffer_kwargs={}): + VideoOutput.setup(self, buffer_kwargs=buffer_kwargs) + flags = 0 + if self.noframe: + flags = pygame.NOFRAME + self.window = pygame.display.set_mode((self.width, self.height), flags) + pygame.display.set_caption(os.path.basename(self.path)) + + def check_events(self, t): + for event in pygame.event.get(): + if event.type == pygame.QUIT: + self.running = False + break + elif event.type == pygame.KEYDOWN: + if event.key == pygame.K_ESCAPE: + self.running = False + break + + def blit_current_frame(self, update=True): + frame = VideoReader.convert_frame(self.video[self.cursor], (self.width, self.height)) + self.window.blit(pygame.surfarray.make_surface(frame), (0, 0)) + if update: + pygame.display.flip() + + def update(self, t): + self.check_events(t) + if self.time_of_previous_frame is not None and (t - self.time_of_previous_frame) < 1 / self.video.fps: + time.sleep(.001) + return + self.time_of_previous_frame = t + self.increment() + self.blit_current_frame(update=True) + + def run(self): + self.setup() + while self.running: + t = time.time() + self.update(t) + self.close() + + def close(self): + VideoOutput.close(self) \ No newline at end of file diff --git a/beatviewer/video/video_reader.py b/beatviewer/video/video_reader.py new file mode 100644 index 0000000..e91a796 --- /dev/null +++ b/beatviewer/video/video_reader.py @@ -0,0 +1,70 @@ +import logging + +import cv2 +import numpy + + +class VideoReader: + + def __init__(self, path): + self.path = path + self.capture = None + self.cursor = None + self.width = None + self.height = None + self.fps = None + self.frame_count = None + + def open(self): + logging.info("Opening video capture for path %s", self.path) + self.capture = cv2.VideoCapture(self.path) + self.cursor = 0 + self.initialize_properties() + + def compute_frame_count(self, margin=5): + frame_count_estimate = int(self.capture.get(cv2.CAP_PROP_FRAME_COUNT)) + self.capture.set(cv2.CAP_PROP_POS_FRAMES, frame_count_estimate - margin) + frame_count = frame_count_estimate - margin + while True: + success, _ = self.capture.read() + if success: + frame_count += 1 + else: + break + self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.cursor) + self.frame_count = frame_count + + def initialize_properties(self): + self.width = int(self.capture.get(cv2.CAP_PROP_FRAME_WIDTH)) + self.height = int(self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) + self.fps = self.capture.get(cv2.CAP_PROP_FPS) + self.compute_frame_count() + logging.info("Video properties: %dx%d, %d frames, %.2f FPS", self.width, self.height, self.frame_count, self.fps) + + def read_frame(self, i=None): + if i is None: + i = self.cursor + while i < 0: + i += self.frame_count + i = i % self.frame_count + if i != self.cursor: + self.cursor = i + self.capture.set(cv2.CAP_PROP_POS_FRAMES, self.cursor) + success, frame = self.capture.read() + if success: + self.cursor += 1 + else: + logging.error("Could not read video frame %d", self.cursor) + return frame + + @staticmethod + def convert_frame(frame, scale=None, transpose=True): + f = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + if scale is not None: + f = cv2.resize(f, scale) + if transpose: + return numpy.transpose(f, axes=(1, 0, 2)) + return f + + def close(self): + self.capture.release() \ No newline at end of file diff --git a/beatviewer/video/video_stream.py b/beatviewer/video/video_stream.py new file mode 100644 index 0000000..6ca1edc --- /dev/null +++ b/beatviewer/video/video_stream.py @@ -0,0 +1,24 @@ +import pyvirtualcam + +from .video_reader import VideoReader +from .video_output import VideoOutput + + +class VideoStream(VideoOutput): + + def __init__(self, path, size=900, fps=60): + VideoOutput.__init__(self, path, size) + self.camera = None + self.fps = fps + + def setup(self, buffer_kwargs={}): + VideoOutput.setup(self, buffer_kwargs=buffer_kwargs) + self.camera = pyvirtualcam.Camera(self.width, self.height, self.fps) # TODO: Which FPS value to set? + + def blit_current_frame(self, update=True): + frame = VideoReader.convert_frame(self.video[self.cursor], (self.width, self.height), transpose=False) + self.camera.send(frame) + + def close(self): + VideoOutput.close(self) + self.camera.close() \ No newline at end of file diff --git a/beatviewer/web/fireworks.html b/beatviewer/web/fireworks.html new file mode 100644 index 0000000..91425de --- /dev/null +++ b/beatviewer/web/fireworks.html @@ -0,0 +1,179 @@ + + + + + + + Fireworks + + + + + + + + + + \ No newline at end of file diff --git a/beatviewer/web/fluid.html b/beatviewer/web/fluid.html new file mode 100644 index 0000000..23c9474 --- /dev/null +++ b/beatviewer/web/fluid.html @@ -0,0 +1,338 @@ + + + + + + + Euler Fluid + + + + + + + + + + \ No newline at end of file diff --git a/beatviewer/web/socket.js b/beatviewer/web/socket.js new file mode 100644 index 0000000..b0ced7d --- /dev/null +++ b/beatviewer/web/socket.js @@ -0,0 +1,92 @@ +class ArgumentParser { + constructor() { + this.arguments = []; + } + + add_argument(name, default_, type, choices=null) { + this.arguments.push({ + name: name, + default: default_, + type: type, + choices: choices + }); + } + + parse_args() { + let params = new URLSearchParams(window.location.search); + let args = {}; + this.arguments.forEach(arg => { + let value = arg.default; + if (params.has(arg.name)) { + let raw_value = params.get(arg.name); + if (arg.type == "string") { + value = raw_value; + } else if (arg.type == "int") { + value = parseInt(raw_value); + } else if (arg.type == "float") { + value = parseFloat(raw_value); + } + } + if (arg.choices && !arg.choices.includes(value)) { + value = arg.default; + } + args[arg.name] = value; + }); + console.log("Parsed args:", args); + return args; + } + +} + +function parse_args(defaults) { + let params = new URLSearchParams(window.location.search); + let args = {}; + for (let key in defaults) { + let reference = defaults[key]; + if (params.has(key)) { + let value = params.get(key); + if (typeof reference === "string") { + args[key] = value; + } else { + args[key] = parseFloat(value); + } + } else { + args[key] = reference; + } + } + return args; +} + +function connect_socket_server(server_uri, beat_callback, onset_callback, bpm_callback) { + const socket = new WebSocket(server_uri); + socket.binaryType = "arraybuffer"; + + socket.addEventListener("open", () => { + console.log("Connected to socket server!"); + }); + + socket.addEventListener("error", () => { + console.warn("Could not connect to socket server, retrying in 1s"); + setTimeout(() => { + connect_socket_server(server_uri, beat_callback, onset_callback, bpm_callback); + }, 1000); + }); + + socket.addEventListener("message", (event) => { + const view = new DataView(event.data); + const value = view.getInt16(0, false); + if (value == 0) { + if (beat_callback) beat_callback(); + } else if (value == 1) { + if (onset_callback) onset_callback(); + } else { + if (bpm_callback) bpm_callback(value); + } + socket.send("k"); + }); + + socket.addEventListener("close", () => { + console.warn("Socket was closed"); + }); + +} diff --git a/config.txt b/config.txt new file mode 100644 index 0000000..42cf38a --- /dev/null +++ b/config.txt @@ -0,0 +1,179 @@ +# ---------------------------------------------------------------------------- # +# SPECTRAL FLUX # +# -----------------------------------------------------------------------------# + +# Audio window size for computing FFT. +# Default: 1024 +audio_window_size 1024 + +# Number of new samples in the window at each iteration. It will set the +# sampling rate for the onset strength signal. Given the audio sampling rate Fs, +# and the hop size H, the OSS sampling rate will be FsO = Fs / H. For +# Fs = 44100 and H = 128, we have FsO = 344.53 Hz. +# Default: 128 +audio_hop_size 128 + +# The spectral flux is compressed to reduce the dynamic range of the signal, and +# adapt it to the human hearing mechanism which is logarithmically sensitive to +# amplitude. Set to 0 to ignore compression. Greater values (1000) will deaden +# strong values and make lower values have more impact. +# Default: 1 +compression_gamma 1 + +# After compression, frequency bins with levels below this threshold are set to +# zero. The value is specified in dB. +# Default: -74 +noise_cancellation_level -74 + +# The width of windowing function applied to the spectral flux, to make it +# smoother. This acts as a low-pass filter. The greater the width, the lower +# the cutoff frequency will be. At 15, it is about 7 Hz. +# Default: 15 +hamming_window_size 15 + + +# ---------------------------------------------------------------------------- # +# ONSET STRENGTH SIGNAL # +# -----------------------------------------------------------------------------# + +# Number of OSS samples used to compute the OSS mean and the OSS variance. +# Default: 1024 +oss_buffer_size 1024 + +# If the OSS becomes greater than this number of standard deviation above the +# mean, an onset is detected. +# Default: 0.1 +onset_threshold 0.1 + +# If the variance is too small, this absolute threshold is used. +# Default: 5.0 +onset_threshold_min 5.0 + + +# ---------------------------------------------------------------------------- # +# TEMPO ESTIMATION # +# -----------------------------------------------------------------------------# + +# Number of OSS samples used to estimate the tempo. +# Default: 2048 +oss_window_size 2048 + +# Number of new samples in the window at each iteration. If FsO is the OSS +# sampling rate and H is the hop size, a new tempo is estimated with rate +# FsO / H. With FsO = 344.53 Hz, this yields 2.7 Hz. +# Default: 128 +oss_hop_size 128 + +# The OSS is autocorrelated to find tempo lag candidates. This is computed by +# performing an FFT and a IFFT on the OSS. A power compression is applied in +# the frequency domain. Smaller values will increase the lag resolution but +# negatively impact noise. +# Default: 0.5 +frequency_domain_compression 0.5 + +# Minimum BPM detected. +# Default: 50 +min_bpm_detection 50 + +# Maximum BPM detected. +# Default: 210 +max_bpm_detection 210 + +# Number of tempo candidates considered when estimating tempo. +# Default: 10 +tempo_candidates 10 + +# Detected tempi are added to an accumulated sum. This sum decreases overtime to +# allow for tempo variation detection. The greater the value (0.99, 0.999) the +# more stable the estimator is, but the longer it takes for new tempi to be +# detected. +# Default: 0.9 +tempo_accumulator_decay 0.9 + +# The tempo accumulated sum is made of gaussian curves centered on each detected +# tempi. This gaussian width allows for getting over slight variations. +# Default: 10 +tempo_accumulator_gaussian_width 10 + +# If the result BPM is lower than this, it gets doubled. +# Default: 90 +min_bpm_rescaled 90 + +# If the result BPM is greater than this, it gets halved. +# Default: 180 +max_bpm_rescaled 180 + + +# ---------------------------------------------------------------------------- # +# CUMULATIVE BEAT STRENGTH SIGNAL # +# -----------------------------------------------------------------------------# + +# Number of CBSS samples used to determined the previous beat location. +# Default: 512 +cbss_buffer_size 512 + +# The log-gaussian width around previous beat locations. +# Default: 300 +cbss_eta 300 + +# Trade-off between the OSS and a pure periodic signal. It takes values between +# 0 and 1. At 0, only the OSS is considered. At 1, only the periodic signal is +# considered. +# Default: 0.9 +cbss_alpha 0.9 + + +# ---------------------------------------------------------------------------- # +# BEAT PREDICTION SIGNAL # +# -----------------------------------------------------------------------------# + +# Offline latency correction factor, in number of OSS samples. See Section 6.1. +# of *Musical Robot Swarms and Equilibria* (Krzyżaniak, 2020) for details. +# Default: 0 +bps_epsilon_o 0 + +# Realtime latency correction factor, in number of OSS samples. See Section 6.2. +# of *Musical Robot Swarms and Equilibria* (Krzyżaniak, 2020) for details. +# Default: 0 +bps_epsilon_r 0 + +# Beat trigger index. Greater values means detecting beats earlier. +# Default: 20 +bps_epsilon_t 20 + +# Width of the gaussian representing the next beat locations. +# Default: 10 +bps_gaussian_width 10 + +# Number of samples for which beat locations are predicted, in the future. As +# this is a cumulative process, bigger buffer will result in a more stable +# behavior. +# Default: 512 +bps_buffer_size 512 + +# Ratio of samples ignored right after a beat is detected, relative to the +# tempo lag (ie. the number of samples between two beats). +# Default: 0.4 +bps_cooldown_ratio 0.4 + + +# ---------------------------------------------------------------------------- # +# KEY MAP # +# -----------------------------------------------------------------------------# + +# Increase the value of bps_epsilon_t. +# Default: page up +key_trigger_beats_earlier page up + +# Decrease the value of bps_epsilon_t. +# Default: page down +key_trigger_beats_later page down + +# Change tracking mode to default. +# Default: f9 +key_set_mode_regular f9 + +# Change tracking mode to tempo locked, where current BPM is locked and CBSS +# will only depend on the so generated pulse train. +# Default: f10 +key_set_mode_tempo_locked f10 \ No newline at end of file diff --git a/obs_beatviewer.py b/obs_beatviewer.py new file mode 100644 index 0000000..e513fe5 --- /dev/null +++ b/obs_beatviewer.py @@ -0,0 +1,493 @@ +import contextlib +import os +import random +import socket + +import obspython as obs + + +ST_SERVER_HOST = "server_host" +ST_SERVER_PORT = "server_port" +ST_BTN_CONNECT = "btn_connect" +ST_BTN_DISCONNECT = "btn_disconnect" +ST_SOCKET_SERVER = "socket_server" +ST_DEBUG_SOURCE = "debug_text_source" +ST_BTN_REFRESH_SOURCES = "btn_refresh_sources" +ST_BTN_BEAT = "btn_beat" +ST_BTN_ONSET = "btn_onset" + + +@contextlib.contextmanager +def source_ar(source_name): + try: + source = obs.obs_get_source_by_name(source_name) + except: + print("Source '%s' does not exist" % source_name) + return + try: + yield source + finally: + obs.obs_source_release(source) + + +@contextlib.contextmanager +def data_ar(source_settings=None): + if not source_settings: + settings = obs.obs_data_create() + if source_settings: + settings = obs.obs_source_get_settings(source_settings) + try: + yield settings + finally: + obs.obs_data_release(settings) + + +def populate_list_property_with_source_names(list_property): + sources = obs.obs_enum_sources() + obs.obs_property_list_clear(list_property) + for source in sources: + name = obs.obs_source_get_name(source) + obs.obs_property_list_add_string(list_property, name, name) + obs.source_list_release(sources) + + +class Visualizer: + + SHORT_NAME = None + ST_SOURCE = None + + COLOR_FILTER_NAME = "Automatic Color Filter" + + def __init__(self): + self.source_name = None + self.source = None + self.active = False + self.color_filter = None + self.previous_opacity = None + + def defaults(self, settings): + pass + + def create_properties(self, controller, props): + pass + + def create_or_identify_color_filter(self): + if self.source is None: + return + existing_color_filter = obs.obs_source_get_filter_by_name(self.source, self.COLOR_FILTER_NAME) + if existing_color_filter is None: + self.color_filter = obs.obs_source_create_private("color_filter", self.COLOR_FILTER_NAME, None) + obs.obs_source_filter_add(self.source, self.color_filter) + else: + self.color_filter = existing_color_filter + + def release(self): + if self.color_filter is not None: + obs.obs_source_release(self.color_filter) + self.color_filter = None + if self.source is not None: + obs.obs_source_release(self.source) + self.source = None + + def create_source(self, settings): + self.release() + self.release() + self.source = obs.obs_get_source_by_name(self.source_name) + self.create_or_identify_color_filter() + + def update(self, settings): + was_active = self.active + self.active = obs.obs_data_get_bool(settings, self.SHORT_NAME) + if was_active and not self.active: + self.stop() + old_source_name = self.source_name + self.source_name = obs.obs_data_get_string(settings, self.ST_SOURCE) + if old_source_name != self.source_name: + self.create_source(settings) + + def set_opacity(self, opacity): + if opacity == self.previous_opacity: + return + self.previous_opacity = opacity + with data_ar() as settings: + obs.obs_data_set_int(settings, "opacity", opacity) + obs.obs_source_update(self.color_filter, settings) + + def handle_beat(self, seconds): + pass + + def handle_onset(self, seconds): + pass + + def handle_bpm(self, bpm, seconds): + pass + + def tick(self, seconds): + pass + + def stop(self): + pass + + +class SeekOnBeatVisualizer(Visualizer): + + SHORT_NAME = "sob" + ST_SOURCE = "sob_source" + + def __init__(self): + Visualizer.__init__(self) + self.duration = None + + def defaults(self, settings): + obs.obs_data_set_default_string(settings, self.ST_SOURCE, "SeekOnBeat") + + def create_properties(self, controller, props): + group = obs.obs_properties_create() + controller.add_source_list(group, self.ST_SOURCE, "Source name") + obs.obs_properties_add_group(props, self.SHORT_NAME, "Seek On Beat", obs.OBS_GROUP_CHECKABLE, group) + + def update(self, settings): + Visualizer.update(self, settings) + self.duration = obs.obs_source_media_get_duration(self.source) + print("New SeekOnBeat duration:", self.duration) + + def handle_beat(self, seconds): + Visualizer.handle_beat(self, seconds) + if not self.active: + return + if self.duration is not None and self.duration >= 1: + obs.obs_source_media_set_time(self.source, random.randint(0, int(self.duration) - 1)) + + +class BlinkingSlideshowVisualizer(Visualizer): + + SHORT_NAME = "bs" + ST_SOURCE = "bs_source" + ST_FOLDER = "bs_folder" + ST_DURATION = "bs_duration" + ST_RANDOM = "bs_random" + ST_RELATIVE = "bs_relative" + ST_AUTOSCALE = "bs_autoscale" + + def __init__(self): + Visualizer.__init__(self) + self.folder = "" + self.images = [] + self.index = 0 + self.visible = False + self.blink_duration = 0.1 + self.random_index = False + self.bpm = None + self.relative_to_bpm = False + self.time_of_previous_beat = 0 + self.auto_scale = True + self.scale_on_next_tick = 0 + + def defaults(self, settings): + obs.obs_data_set_default_string(settings, self.ST_SOURCE, "BlinkingSlideshow") + obs.obs_data_set_default_string(settings, self.ST_FOLDER, self.folder) + obs.obs_data_set_default_bool(settings, self.ST_RANDOM, self.random_index) + obs.obs_data_set_default_int(settings, self.ST_DURATION, int(self.blink_duration * 1000)) + obs.obs_data_set_default_bool(settings, self.ST_RELATIVE, self.relative_to_bpm) + obs.obs_data_set_default_bool(settings, self.ST_AUTOSCALE, self.auto_scale) + + def create_properties(self, controller, props): + group = obs.obs_properties_create() + controller.add_source_list(group, self.ST_SOURCE, "Source name") + obs.obs_properties_add_path(group, self.ST_FOLDER, "Images Folder", obs.OBS_PATH_DIRECTORY, None, None) + obs.obs_properties_add_int(group, self.ST_DURATION, "Blinking Duration (ms)", 1, 1000, 1) + obs.obs_properties_add_bool(group, self.ST_RELATIVE, "Duration relative to BPM (%)") + obs.obs_properties_add_bool(group, self.ST_RANDOM, "Random Index Jumps") + obs.obs_properties_add_bool(group, self.ST_AUTOSCALE, "Automatic Scaling") + obs.obs_properties_add_group(props, self.SHORT_NAME, "Blinking Slideshow", obs.OBS_GROUP_CHECKABLE, group) + + def scale(self): + current_scene = obs.obs_scene_from_source(obs.obs_frontend_get_current_scene()) + if current_scene: + scene_item = obs.obs_scene_find_source(current_scene, self.source_name) + if scene_item: + obs.obs_sceneitem_set_bounds_type(scene_item, obs.OBS_BOUNDS_SCALE_INNER) + video_info = obs.obs_video_info() + obs.obs_get_video_info(video_info) + pos = obs.vec2() + pos.x = 0 + pos.y = 0 + obs.obs_sceneitem_set_pos(scene_item, pos) + bounds = obs.vec2() + bounds.x = video_info.base_width + bounds.y = video_info.base_height + obs.obs_sceneitem_set_bounds(scene_item, bounds) + + def create_source(self, settings): + Visualizer.create_source(self, settings) + if self.auto_scale: + self.scale() + + def load_images(self): + if not os.path.isdir(self.folder): + return + self.index = 0 + self.images = sorted([ + os.path.join(self.folder, path) + for path in next(os.walk(self.folder))[2] + ]) + print("BlinkingSlideshow folder contains %d images" % len(self.images)) + + def update(self, settings): + Visualizer.update(self, settings) + self.random_index = obs.obs_data_get_bool(settings, self.ST_RANDOM) + duration_input_value = obs.obs_data_get_int(settings, self.ST_DURATION) + if self.relative_to_bpm and self.bpm is not None: + self.blink_duration = (duration_input_value / 100) * 60 / self.bpm + else: + self.blink_duration = duration_input_value / 1000 + self.set_opacity(0) + old_folder = self.folder + self.folder = obs.obs_data_get_string(settings, self.ST_FOLDER) + if old_folder != self.folder: + print("New BlinkingSlideshow folder:", self.folder) + self.load_images() + + def handle_beat(self, seconds): + if not self.active: + return + self.time_of_previous_beat = seconds + self.load_next_image() + self.set_opacity(100) + + def handle_bpm(self, bpm, seconds): + self.bpm = bpm + + def load_next_image(self): + if len(self.images) > 0: + with data_ar() as settings: + obs.obs_data_set_string(settings, "file", os.path.realpath(self.images[self.index])) + obs.obs_source_update(self.source, settings) + if self.auto_scale: + self.scale() + if self.random_index: + self.index = random.randint(0, len(self.images) - 1) + else: + self.index = (self.index + 1) % len(self.images) + + def tick(self, seconds): + if not self.active: + return + progress = min(1, max(0, (seconds - self.time_of_previous_beat) / self.blink_duration)) + opacity = int((1 - progress ** 4) * 100) + self.set_opacity(opacity) + + def stop(self): + self.set_opacity(0) + + +class Controller: + + def __init__(self): + self.host = "localhost" + self.port = 8765 + self.client = None + self.connected = False + self.debug_source_name = None + self.bpm = None + self.timestamp = 0 + self.source_lists = [] + self.visualizers = [ + SeekOnBeatVisualizer(), + BlinkingSlideshowVisualizer() + ] + + def defaults(self, settings): + obs.obs_data_set_default_string(settings, ST_SERVER_HOST, self.host) + obs.obs_data_set_default_int(settings, ST_SERVER_PORT, self.port) + obs.obs_data_set_default_string(settings, ST_DEBUG_SOURCE, "BeatviewerDebug") + for visualizer in self.visualizers: + visualizer.defaults(settings) + + def _create_server_properties(self, props): + def callback_connect(*args): + self.connect() + def callback_disconnect(*args): + self.disconnect() + group = obs.obs_properties_create() + obs.obs_properties_add_text(group, ST_SERVER_HOST, "Host", obs.OBS_TEXT_DEFAULT) + obs.obs_properties_add_int(group, ST_SERVER_PORT, "Port", 0, 65535, 1) + obs.obs_properties_add_button(group, ST_BTN_CONNECT, "Connect", callback_connect) + obs.obs_properties_add_button(group, ST_BTN_DISCONNECT, "Disonnect", callback_disconnect) + obs.obs_properties_add_group(props, ST_SOCKET_SERVER, "Socket Server", obs.OBS_GROUP_NORMAL, group) + + def create_properties(self, props): + def callback_refresh(*args): + self.refresh_source_lists() + def callback_beat(*args): + self.handle_beat() + def callback_onset(*args): + self.handle_onset() + obs.obs_properties_add_button(props, ST_BTN_REFRESH_SOURCES, "Refresh Sources", callback_refresh) + obs.obs_properties_add_button(props, ST_BTN_BEAT, "Beat", callback_beat) + obs.obs_properties_add_button(props, ST_BTN_ONSET, "Onset", callback_onset) + self.add_source_list(props, ST_DEBUG_SOURCE, "Debugging Text Source") + self._create_server_properties(props) + for visualizer in self.visualizers: + visualizer.create_properties(self, props) + self.refresh_source_lists() + self.update_debug_text() + + def update_debug_text(self): + with source_ar(self.debug_source_name) as source, data_ar() as settings: + string = "BeatViewer: " + if self.connected: + string += "connected " + else: + string += "disconnected " + if self.bpm is not None: + string += f"// {self.bpm} BPM " + obs.obs_data_set_string(settings, "text", string.strip()) + obs.obs_source_update(source, settings) + + def connect(self): + print(f"Connecting socket client to {self.host}:{self.port}") + if self.client is not None: + self.disconnect() + try: + self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.client.connect((self.host, self.port)) + self.client.setblocking(False) + self.connected = True + print("Connected to server") + except (ConnectionRefusedError, OSError): + print("Could not connect to server") + self.client = None + self.connected = False + self.update_debug_text() + + def disconnect(self): + print("Disconnecting socket client") + if self.client is not None: + self.client.close() + self.client = None + self.connected = False + for visualizer in self.visualizers: + visualizer.stop() + self.update_debug_text() + + def add_source_list(self, props, name, description): + source_list = obs.obs_properties_add_list(props, name, description, obs.OBS_COMBO_TYPE_LIST, obs.OBS_COMBO_FORMAT_STRING) + self.source_lists.append(source_list) + populate_list_property_with_source_names(source_list) + + def refresh_source_lists(self): + for source_list in self.source_lists: + populate_list_property_with_source_names(source_list) + + def update(self, settings): + print("Updating controller") + host = obs.obs_data_get_string(settings, ST_SERVER_HOST) + port = obs.obs_data_get_int(settings, ST_SERVER_PORT) + if host != self.host or port != self.port: + self.host = host + self.port = port + if self.connected: + self.connect() + debug_source_name = obs.obs_data_get_string(settings, ST_DEBUG_SOURCE) + if debug_source_name != self.debug_source_name: + self.debug_source_name = debug_source_name + self.update_debug_text() + for visualizer in self.visualizers: + visualizer.update(settings) + + def unload(self): + if not self.connected: + self.disconnect() + for visualizer in self.visualizers: + visualizer.release() + + def handle_beat(self): + for visualizer in self.visualizers: + visualizer.handle_beat(self.timestamp) + + def handle_onset(self): + for visualizer in self.visualizers: + visualizer.handle_onset(self.timestamp) + + def handle_bpm(self, bpm): + if bpm != self.bpm: + self.bpm = bpm + self.update_debug_text() + for visualizer in self.visualizers: + visualizer.handle_bpm(bpm, self.timestamp) + + def handle_packet(self, packet): + if packet == b"\x00\x00": + self.handle_beat() + elif packet == b"\x00\x01": + self.handle_onset() + else: + bpm = int.from_bytes(packet, byteorder="big", signed=False) + self.handle_bpm(bpm) + + def tick(self, seconds): + self.timestamp += seconds + if self.client is not None and self.connected: + try: + packet = self.client.recv(2) + self.handle_packet(packet) + except BlockingIOError: + pass + except (ConnectionAbortedError, ConnectionRefusedError, ConnectionResetError): + print("Socket server just closed") + self.disconnect() + return + for visualizer in self.visualizers: + visualizer.tick(self.timestamp) + + +c = Controller() + + +############################################################################### +# STARTUP # +############################################################################### + + +def script_defaults(settings): + global c + c.defaults(settings) + + +def script_description(): + return ( + "BeatViewer. Track beats in a music stream. To get started, start the external program with the socket handler." + ) + + +def script_update(settings): + global c + c.update(settings) + + +def script_properties(): + global c + props = obs.obs_properties_create() + c.create_properties(props) + return props + + +############################################################################### +# RUNTIME # +############################################################################### + + +def script_tick(seconds): + global c + c.tick(seconds) + + +############################################################################### +# CLOSURE # +############################################################################### + + +def script_unload(): + global c + c.unload() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..6b73c07 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,11 @@ +keyboard +matplotlib +numpy +opencv-python +pygame +pyvirtualcam +scipy +sounddevice +soundfile +tqdm +websockets \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..1c72df3 --- /dev/null +++ b/setup.py @@ -0,0 +1,34 @@ +import os +from setuptools import find_packages, setup + +with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: + README = readme.read() + +# allow setup.py to be run from any path +os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) + +setup( + name='beatviewer', + version='1.0.0', + packages=find_packages(), + include_package_data=True, + license='GNU GPLv3', + description='A beat tracking algorithm with visualizations', + long_description=README, + url='https://chalier.fr/', + author='Yohan Chalier', + author_email='yohan@chalier.fr', + install_requires=[ + "keyboard", + "matplotlib", + "numpy", + "opencv-python", + "pygame", + "pyvirtualcam", + "scipy", + "sounddevice", + "soundfile", + "tqdm", + "websockets", + ], +) \ No newline at end of file