Free, open-source real-time voice changer for Windows: 20 live voices, local AI voice conversion (Seed-VC on ONNX Runtime), soundboard, virtual mic, hotkeys.
VoxShift 0.2.0: free, open-source real-time voice changer for Windows
skyef345879ce3e
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..af9ef0d--- /dev/null+++ b/.gitignore@@ -0,0 +1,14 @@+.venv/+__pycache__/+*.pyc+.pytest_cache/+# never commit binaries+*.exe+*.dll+# downloaded / exported weights and renders+models/+checkpoints/+*.onnx+*.pth+renders/+build/diff --git a/.gitmodules b/.gitmodulesnew file mode 100644index 0000000..2d65de7--- /dev/null+++ b/.gitmodules@@ -0,0 +1,3 @@+[submodule "third_party/seed-vc"]+ path = third_party/seed-vc+ url = https://github.com/Plachtaa/seed-vc.gitdiff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..e72bfdd--- /dev/null+++ b/LICENSE@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+ 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.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ 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 <https://www.gnu.org/licenses/>.++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:++ <program> Copyright (C) <year> <name of author>+ 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+<https://www.gnu.org/licenses/>.++ 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+<https://www.gnu.org/licenses/why-not-lgpl.html>.\ No newline at end of filediff --git a/README.md b/README.mdnew file mode 100644index 0000000..4b2bd7b--- /dev/null+++ b/README.md@@ -0,0 +1,154 @@+<p align="center"><img src="voxshift/assets/voxshift.png" width="96" alt="VoxShift"></p>++# VoxShift++**VoxShift is a free, open-source real-time voice changer for Windows and an+alternative to commercial voice changers.** It offers the features you'd+expect from those apps:+* Live voice effects+* AI voice conversion+* A soundboard+* A virtual microphone for Discord, OBS and games+* Hotkeys and a tray icon++Everything runs locally on your PC. There's no account, subscription or+telemetry.++## Download++Get **`VoxShift-Setup-<version>.exe`** from+[Releases](../../releases/latest) and run it.++* **Per-user install.** It goes into `%LOCALAPPDATA%\Programs\VoxShift`, with shortcuts and an uninstaller. The app itself needs no admin rights.+* **Virtual microphone.** Leave **"Install the virtual microphone"** checked. Setup downloads the free [VB-CABLE](https://vb-audio.com/Cable/) driver from vb-audio.com and only runs it if VB-Audio's code signature checks out. Approve the two Windows prompts (admin + driver), once.+* In Discord, OBS or your game, choose **CABLE Output (VB-Audio Virtual Cable)** as the microphone.++> The installer isn't code-signed yet, so Windows SmartScreen may say+> "unrecognized app". Choose **More info → Run anyway**.++## Features++- [x] **20 real-time voices**: robot, demon, deep, chipmunk, male↔female, radio, telephone, megaphone, cave, alien, ghost, auto-tune and more.+- [x] **AI voices from your own recording.** Click **New AI voice**, then pick a clip or record 10 s of someone talking. It uses Seed-VC (Whisper encoder → diffusion transformer → BigVGAN) running locally on ONNX Runtime + DirectML, so it works on any DirectX 12 GPU.+- [x] **Soundboard**: point it at a folder of sounds and they mix into your mic.+- [x] **Virtual microphone** (VB-CABLE), plus **hear myself** monitoring on your headphones.+- [x] **Global hotkeys**: <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>F9</kbd> voice changer · <kbd>F10</kbd> hear myself · <kbd>F11</kbd> mute mic · <kbd>F12</kbd> stop sounds. You can change them in Settings.+- [x] **Tray icon**, start with Windows, remembers your devices and last voice.+- [x] **Make your own voices**: every effect is a small JSON file of DSP nodes. See [Custom voices](#custom-voices).+- [x] **100 % offline and private**: no account, no telemetry, no cloud processing.+- [x] **Command line** too: `voxshift-cli convert in.wav out.wav -v demon`.++## How it compares++| | **VoxShift** | Typical commercial voice changer |+|---|:---:|:---:|+| Price | ✅ Free | 💲 Free tier + subscription |+| Open source | ✅ | ❌ |+| Account required | ✅ No | ❌ Usually |+| Works offline | ✅ Fully | ⚠️ Often needs sign-in / online voice library |+| Telemetry / analytics | ✅ None | ⚠️ Common |+| Real-time voice effects | ✅ 20 built in | ✅ Usually hundreds |+| AI voice from your own recording | ✅ Local, unlimited | ⚠️ Often paid or cloud |+| Make / edit your own effects | ✅ JSON voice graphs | ⚠️ Limited |+| Soundboard | ✅ | ✅ |+| Virtual microphone | ✅ via free VB-CABLE | ✅ own driver |+| Hotkeys + tray | ✅ | ✅ |+| macOS | ❌ (Windows app; the CLI runs elsewhere) | ⚠️ Varies |++**Where commercial apps are still ahead:**+* They have much bigger, professionally designed voice libraries.+* Their virtual mic needs no separate driver install.+* AI voice latency is lower. VoxShift's AI voices lag about 1 s on DirectML, while its regular effects stay under 100 ms.+* Their UIs are more polished.++Pull requests welcome.++## Measured (RTX 5070 Laptop, 48 kHz)++| voice | CPU/GPU load (real-time factor) | algorithmic latency |+|---|---|---|+| radio, telephone | 0.002 | 0 ms |+| deep, male↔female, auto-tune | ≈0.02 | 43 ms |+| cave, demon, ghost (convolution reverb) | 0.08–0.12 | 0–43 ms |+| AI voice, ONNX Runtime + DirectML, 6 steps | 0.65–0.79 | ≈1 s end to end |++AI quality was measured as speaker similarity to the target recording+(CAMPPlus embeddings, 0–1):++| clip | similarity |+|---|---|+| your own voice, unconverted | 0.45 |+| VoxShift's AI voice | 0.81 |+| two halves of the same target recording | 0.85 |++## Custom voices++Put a `.json` file in `%APPDATA%\VoxShift\voices\` and it appears in the+voice list:++```json+{+ "name": "Haunted Radio",+ "category": "my voices",+ "chain": [+ {"type": "FormantPitchShifter", "params": {"semitones": -3, "formant_semitones": -2}},+ {"type": "Biquad", "params": {"kind": "bandpass", "freq": 1500, "q": 0.8}},+ {"type": "RingModulation", "params": {"freq": {"lfo": {"rate": 0.5, "min": 20, "max": 60}}, "mix": 0.4}},+ {"type": "ConvolutionReverb", "params": {"decay_s": 2.5, "mix": 0.35}}+ ]+}+```++Available node types:+* **Filters and dynamics:** Gain, Biquad, ParametricEQ, NoiseGate, Compressor, SoftLimiter.+* **Pitch:** PitchShift, FormantPitchShifter (also does auto-tune).+* **Colour:** Vocoder, Whisperize, Distortion, Bitcrusher, RingModulation, Tremolo, Oscillator.+* **Time and space:** Delay, ModDelay, ConvolutionReverb.+* **Routing:** Parallel (latency-aligned branches).++Any numeric parameter can be modulated with `lfo`, `random` or `sequence`.+See `voxshift/dsp/nodes.py` for every parameter.++## Build from source++You need Python 3.12. An NVIDIA GPU is only needed for the PyTorch developer+path.++```bash+git clone --recurse-submodules https://github.com/Metrix187/voxshift.git+cd voxshift+python -m venv .venv+.venv\Scripts\python -m pip install torch torchaudio --index-url https://download.pytorch.org/whl/cu128+.venv\Scripts\python -m pip install -r requirements.txt pyinstaller pystray pillow sv-ttk+.venv\Scripts\python -m voxshift export-onnx # downloads the open weights, writes models/onnx (~1.2 GB)+.venv\Scripts\python packaging/build.py # build/dist/VoxShift + installer (needs Inno Setup 6)+.venv\Scripts\python -m pytest # 43 tests+```++The developer install can also run the AI voices in PyTorch with a CUDA-graph+solver (`ai-whisper-small`, `ai-realtime`). These have lower latency on+NVIDIA GPUs.++```+voxshift/+ dsp/ streaming STFT, effect nodes, JSON voice graphs + modulators+ ai/ Seed-VC streaming (PyTorch), ONNX export, ONNX Runtime + numpy backend+ audio/ PortAudio engine (mic -> voice -> soundboard -> limiter -> virtual mic + monitor), cable setup+ gui.py desktop app · cli.py command line · settings/paths/winsys: app plumbing+packaging/ PyInstaller spec, Inno Setup script, build.py, icon+```++## Responsible use++AI voices can imitate real people. Only convert to voices you have permission+to use, and don't use VoxShift to deceive, harass or impersonate anyone.++## License and credits++VoxShift is licensed under **GPL-3.0**. Third-party components and model+licenses are listed in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).+* AI voice conversion: [Seed-VC](https://github.com/Plachtaa/seed-vc) (GPL-3.0).+* Vocoder: [BigVGAN](https://github.com/NVIDIA/BigVGAN) (MIT).+* Content encoder: [Whisper](https://huggingface.co/openai/whisper-small) (Apache-2.0).+* Speaker embedding: [CAMPPlus](https://huggingface.co/funasr/campplus) (Apache-2.0).+* Virtual microphone: [VB-CABLE](https://vb-audio.com/Cable/), donationware by VB-Audio, downloaded from their site and not redistributed.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..3b7c16c--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@ -0,0 +1,42 @@+# Third-party notices++VoxShift is GPL-3.0 (see `LICENSE`). The Windows build bundles the+components below. Each remains under its own license; full texts are at the+linked projects.++## AI models (exported to ONNX and shipped in `models/onnx/whisper-small-bigvgan/`)++| component | source | license |+|---|---|---|+| Seed-VC DiT + length regulator (`DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned`) | [Plachta/Seed-VC](https://huggingface.co/Plachta/Seed-VC), code [Plachtaa/seed-vc](https://github.com/Plachtaa/seed-vc) | GPL-3.0 |+| Whisper-small encoder | [openai/whisper-small](https://huggingface.co/openai/whisper-small) | Apache-2.0 |+| BigVGAN v2 22 kHz 80-band vocoder | [nvidia/bigvgan_v2_22khz_80band_256x](https://huggingface.co/nvidia/bigvgan_v2_22khz_80band_256x) | MIT, © NVIDIA |+| CAMPPlus speaker embedding | [funasr/campplus](https://huggingface.co/funasr/campplus) | Apache-2.0 |++The ONNX files are produced from these checkpoints by `voxshift export-onnx`+(`voxshift/ai/onnx_export.py`). The Seed-VC source used to build and export+them is pinned as a git submodule in `third_party/seed-vc`.++## Runtime libraries++| component | license |+|---|---|+| Python 3.12 | PSF License |+| NumPy, SciPy | BSD-3-Clause |+| ONNX Runtime (DirectML build) | MIT, © Microsoft |+| DirectML (`DirectML.dll`, shipped with ONNX Runtime) | Microsoft DirectML redistributable license |+| sounddevice / PortAudio | MIT |+| soundfile / libsndfile | BSD-3-Clause / LGPL-2.1 (dynamically linked) |+| Pillow | MIT-CMU |+| pystray | LGPL-3.0 (dynamically loaded Python module) |+| sv-ttk (Sun Valley theme) | MIT |+| Tcl/Tk | Tcl/Tk License |+| OpenSSL, libffi (bundled with Python) | Apache-2.0, MIT |+| PyInstaller bootloader | GPL-2.0 with bootloader exception |++## Not bundled++**VB-CABLE** (virtual audio cable) by VB-Audio Software is donationware. The+installer downloads it from vb-audio.com at install time and runs it only+after verifying VB-Audio's Authenticode signature. It is not redistributed+with VoxShift.diff --git a/packaging/build.py b/packaging/build.pynew file mode 100644index 0000000..28b1fa6--- /dev/null+++ b/packaging/build.py@@ -0,0 +1,71 @@+"""Build the standalone app (and its installer when Inno Setup is available).++ python packaging/build.py # -> build/dist/VoxShift/ (+ build/VoxShift-Setup-<ver>.exe)+ python packaging/build.py --no-installer++Requires the dev environment once, to export the AI model to ONNX+(`python -m voxshift export-onnx`); the resulting app needs no Python,+PyTorch or internet connection.+"""+from __future__ import annotations++import argparse+import shutil+import subprocess+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+BUILD = ROOT / "build"+DIST = BUILD / "dist" / "VoxShift"+MODEL = ROOT / "models" / "onnx" / "whisper-small-bigvgan"+MODEL_FILES = ["config.json", "features.npz", "whisper_encoder.onnx", "length_regulator.onnx",+ "dit_step.onnx", "campplus.onnx", "vocoder.onnx"]+ISCC_CANDIDATES = [Path(r"C:\Program Files (x86)\Inno Setup 6\ISCC.exe"), Path(r"C:\Program Files\Inno Setup 6\ISCC.exe"),+ Path.home() / r"AppData\Local\Programs\Inno Setup 6\ISCC.exe"]+++def version() -> str:+ ns: dict = {}+ exec((ROOT / "voxshift" / "__init__.py").read_text(), ns)+ return ns["__version__"]+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--no-installer", action="store_true")+ args = ap.parse_args()++ missing = [f for f in MODEL_FILES if not (MODEL / f).is_file()]+ if missing:+ sys.exit(f"AI model not exported ({', '.join(missing)} missing): run `python -m voxshift export-onnx`")+ if not (ROOT / "voxshift" / "assets" / "voxshift.ico").is_file():+ subprocess.run([sys.executable, str(ROOT / "packaging" / "make_icon.py")], check=True)++ print("== PyInstaller")+ subprocess.run([sys.executable, "-m", "PyInstaller", str(ROOT / "packaging" / "voxshift.spec"), "--noconfirm",+ "--distpath", str(BUILD / "dist"), "--workpath", str(BUILD / "work")], check=True)++ print("== AI model")+ dest = DIST / "models" / "onnx" / MODEL.name+ dest.mkdir(parents=True, exist_ok=True)+ for f in MODEL_FILES:+ shutil.copy2(MODEL / f, dest / f)+ for doc in ("LICENSE", "THIRD_PARTY_NOTICES.md"): # licence texts travel with the binaries+ shutil.copy2(ROOT / doc, DIST / doc)+ size = sum(p.stat().st_size for p in DIST.rglob("*") if p.is_file())+ print(f"app folder: {DIST} ({size / 2**30:.2f} GB)")++ if args.no_installer:+ return+ iscc = next((p for p in ISCC_CANDIDATES if p.is_file()), None) or shutil.which("ISCC")+ if not iscc:+ print("Inno Setup (ISCC.exe) not found - skipping the installer. The app folder above runs as-is.")+ return+ print("== Inno Setup")+ subprocess.run([str(iscc), f"/DAppVersion={version()}", f"/DDistDir={DIST}", f"/DOutDir={BUILD}",+ str(ROOT / "packaging" / "voxshift.iss")], check=True)+++if __name__ == "__main__":+ main()diff --git a/packaging/entry_cli.py b/packaging/entry_cli.pynew file mode 100644index 0000000..e73d4e6--- /dev/null+++ b/packaging/entry_cli.py@@ -0,0 +1,4 @@+"""Frozen entry point: voxshift-cli.exe (console tools: convert, live, cable, voices)."""+from voxshift.cli import main++main()diff --git a/packaging/entry_gui.py b/packaging/entry_gui.pynew file mode 100644index 0000000..69572da--- /dev/null+++ b/packaging/entry_gui.py@@ -0,0 +1,6 @@+"""Frozen entry point: VoxShift.exe (windowed desktop app)."""+import sys++from voxshift.gui import main++main(sys.argv[1:])diff --git a/packaging/make_icon.py b/packaging/make_icon.pynew file mode 100644index 0000000..70eaac6--- /dev/null+++ b/packaging/make_icon.py@@ -0,0 +1,38 @@+"""Render the VoxShift icon (assets/voxshift.ico + .png). Run once; outputs are committed."""+from pathlib import Path++from PIL import Image, ImageDraw++OUT = Path(__file__).resolve().parent.parent / "voxshift" / "assets"+S = 512+++def render() -> Image.Image:+ grad = Image.new("RGBA", (S, S))+ px = grad.load()+ a, b = (124, 58, 237), (6, 182, 212) # violet -> cyan+ for y in range(S):+ for x in range(S):+ t = (x + y) / (2 * S - 2)+ px[x, y] = tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(3)) + (255,)+ mask = Image.new("L", (S, S), 0)+ ImageDraw.Draw(mask).rounded_rectangle((16, 16, S - 16, S - 16), radius=112, fill=255)+ img = Image.new("RGBA", (S, S), (0, 0, 0, 0))+ img.paste(grad, (0, 0), mask)+ d = ImageDraw.Draw(img)+ heights = [0.22, 0.42, 0.70, 0.95, 0.62, 0.85, 0.48, 0.28]+ w, gap = 34, 18+ x0 = (S - (len(heights) * w + (len(heights) - 1) * gap)) // 2+ for i, h in enumerate(heights):+ bh = int(h * 300)+ x = x0 + i * (w + gap)+ d.rounded_rectangle((x, S // 2 - bh // 2, x + w, S // 2 + bh // 2), radius=w // 2, fill="white")+ return img+++if __name__ == "__main__":+ OUT.mkdir(parents=True, exist_ok=True)+ img = render()+ img.resize((256, 256), Image.LANCZOS).save(OUT / "voxshift.png")+ img.save(OUT / "voxshift.ico", sizes=[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)])+ print("wrote", OUT / "voxshift.ico")diff --git a/packaging/voxshift.iss b/packaging/voxshift.issnew file mode 100644index 0000000..9003187--- /dev/null+++ b/packaging/voxshift.iss@@ -0,0 +1,77 @@+; VoxShift installer (Inno Setup 6).+; Built by packaging/build.py, which passes AppVersion / DistDir / OutDir.+; Per-user install (%LOCALAPPDATA%\Programs), so the app itself needs no admin rights;+; only the optional virtual-microphone driver asks for elevation.++#ifndef AppVersion+ #define AppVersion "0.0.0"+#endif+#ifndef DistDir+ #define DistDir "..\build\dist\VoxShift"+#endif+#ifndef OutDir+ #define OutDir "..\build"+#endif++[Setup]+AppId={{80A8D700-17F2-43C6-8A8B-6618128A3C70}+AppName=VoxShift+AppVersion={#AppVersion}+AppVerName=VoxShift {#AppVersion}+AppPublisher=VoxShift+DefaultDirName={localappdata}\Programs\VoxShift+DefaultGroupName=VoxShift+DisableProgramGroupPage=yes+PrivilegesRequired=lowest+ArchitecturesAllowed=x64compatible+ArchitecturesInstallIn64BitMode=x64compatible+OutputDir={#OutDir}+OutputBaseFilename=VoxShift-Setup-{#AppVersion}+SetupIconFile=..\voxshift\assets\voxshift.ico+UninstallDisplayIcon={app}\VoxShift.exe+UninstallDisplayName=VoxShift+WizardStyle=modern+; model weights are already dense; fast LZMA keeps build time sane for ~1 GB+Compression=lzma2/fast+SolidCompression=no+CloseApplications=yes+RestartApplications=no++[Tasks]+Name: "vbcable"; Description: "Install the virtual microphone (free VB-CABLE driver from vb-audio.com; Windows will ask for permission)"; Check: not CableInstalled+Name: "desktopicon"; Description: "Create a desktop shortcut"+Name: "autostart"; Description: "Start VoxShift with Windows (in the tray)"; Flags: unchecked++[Files]+Source: "{#DistDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs++[Icons]+Name: "{autoprograms}\VoxShift"; Filename: "{app}\VoxShift.exe"+Name: "{autodesktop}\VoxShift"; Filename: "{app}\VoxShift.exe"; Tasks: desktopicon++[Registry]+Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; ValueName: "VoxShift"; ValueData: """{app}\VoxShift.exe"" --minimized"; Flags: uninsdeletevalue; Tasks: autostart++[Run]+; 1) download the official VB-CABLE pack and refuse it unless its Authenticode signature is VB-Audio's;+; 2) Setup itself runs the verified driver setup elevated (-i -h = install, hidden UI). Requesting elevation+; from this visible wizard keeps the UAC prompt in front; Windows also asks for driver consent once.+Filename: "{app}\voxshift-cli.exe"; Parameters: "cable --download ""{app}\vbcable"""; StatusMsg: "Downloading the virtual microphone driver (VB-CABLE)..."; Flags: runhidden waituntilterminated; Tasks: vbcable+Filename: "{app}\vbcable\VBCABLE_Setup_x64.exe"; Parameters: "-i -h"; WorkingDir: "{app}\vbcable"; StatusMsg: "Installing the virtual microphone - approve the Windows prompts..."; Verb: runas; Flags: shellexec waituntilterminated; Tasks: vbcable; Check: VBCableDownloaded+Filename: "{app}\VoxShift.exe"; Description: "Launch VoxShift"; Flags: nowait postinstall skipifsilent++[UninstallDelete]+Type: filesandordirs; Name: "{app}\_internal"+Type: filesandordirs; Name: "{app}\vbcable"++[Code]+function VBCableDownloaded: Boolean;+begin+ Result := FileExists(ExpandConstant('{app}\vbcable\VBCABLE_Setup_x64.exe'));+end;++function CableInstalled: Boolean;+begin+ { The driver runs from the DriverStore, so look for its service, not a file in System32\drivers. }+ Result := RegKeyExists(HKLM, 'SYSTEM\CurrentControlSet\Services\VBAudioVACMME');+end;diff --git a/packaging/voxshift.spec b/packaging/voxshift.specnew file mode 100644index 0000000..633bbe9--- /dev/null+++ b/packaging/voxshift.spec@@ -0,0 +1,43 @@+# PyInstaller spec: one folder, two executables sharing one runtime.+# VoxShift.exe windowed desktop app+# voxshift-cli.exe console tools (convert / live / cable / voices)+# Build with: python packaging/build.py+import os++from PyInstaller.utils.hooks import collect_dynamic_libs++ROOT = os.path.abspath(os.path.join(SPECPATH, ".."))+ICON = os.path.join(ROOT, "voxshift", "assets", "voxshift.ico")++# Dev-only stacks: the standalone app runs AI voices through ONNX Runtime + numpy.+EXCLUDES = [+ "torch", "torchaudio", "torchvision", "transformers", "tokenizers", "safetensors", "huggingface_hub",+ "librosa", "numba", "llvmlite", "matplotlib", "onnx", "onnxconverter_common", "onnxruntime.transformers",+ "onnxruntime.quantization", "onnxruntime.tools", "pytest", "IPython", "pandas", "sympy", "networkx",+ "jinja2", "munch", "einops", "yaml", "tqdm", "PyInstaller",+]++a = Analysis(+ [os.path.join(SPECPATH, "entry_gui.py"), os.path.join(SPECPATH, "entry_cli.py")],+ pathex=[ROOT],+ binaries=collect_dynamic_libs("onnxruntime"), # onnxruntime.dll + DirectML.dll+ datas=[+ (os.path.join(ROOT, "voxshift", "voices", "*.json"), "voxshift/voices"),+ (os.path.join(ROOT, "voxshift", "assets", "*"), "voxshift/assets"),+ ],+ hiddenimports=["pystray._win32", "PIL._tkinter_finder"],+ excludes=EXCLUDES,+ noarchive=False,+)+pyz = PYZ(a.pure)+++def scripts_without(name):+ return [s for s in a.scripts if s[0] != name]+++gui = EXE(pyz, scripts_without("entry_cli"), [], exclude_binaries=True, name="VoxShift",+ console=False, icon=ICON, upx=False)+cli = EXE(pyz, scripts_without("entry_gui"), [], exclude_binaries=True, name="voxshift-cli",+ console=True, icon=ICON, upx=False)+coll = COLLECT(gui, cli, a.binaries, a.datas, name="VoxShift", upx=False)diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..8e2f4d9--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,30 @@+[build-system]+requires = ["setuptools>=68"]+build-backend = "setuptools.build_meta"++[project]+name = "voxshift"+version = "0.1.0"+description = "Free, local real-time voice changer: DSP voice graphs plus Seed-VC AI voices."+readme = "README.md"+requires-python = ">=3.10"+license = { text = "GPL-3.0-only" }+dependencies = ["numpy>=1.26", "scipy>=1.13", "sounddevice>=0.5", "soundfile>=0.12"]++[project.optional-dependencies]+ai = ["torch", "torchaudio", "librosa>=0.10", "transformers==4.46.3", "huggingface_hub>=0.28,<1.0",+ "munch>=4.0", "einops>=0.8", "pyyaml>=6.0", "matplotlib>=3.8"]+onnx = ["onnx>=1.17", "onnxruntime-directml>=1.20; platform_system == 'Windows'"]+test = ["pytest>=8"]++[project.scripts]+voxshift = "voxshift.cli:main"++[tool.setuptools.packages.find]+include = ["voxshift*"]++[tool.setuptools.package-data]+voxshift = ["voices/*.json"]++[tool.pytest.ini_options]+testpaths = ["tests"]diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..1ee70f4--- /dev/null+++ b/requirements.txt@@ -0,0 +1,20 @@+# PyTorch with CUDA is installed separately (see README):+# pip install torch torchaudio --index-url https://download.pytorch.org/whl/cu128+numpy>=1.26+scipy>=1.13+sounddevice>=0.5+soundfile>=0.12+# AI voices (Seed-VC runtime)+librosa>=0.10+transformers==4.46.3+huggingface_hub>=0.28,<1.0+munch>=4.0+einops>=0.8+pyyaml>=6.0+matplotlib>=3.8+# ONNX export / runner (optional). DirectML runs on any DirectX 12 GPU on Windows;+# on Linux use `onnxruntime-gpu` instead (same Python module).+onnx>=1.17+onnxruntime-directml>=1.20 ; platform_system == "Windows"+# tests+pytest>=8diff --git a/tests/test_cable.py b/tests/test_cable.pynew file mode 100644index 0000000..3fd67af--- /dev/null+++ b/tests/test_cable.py@@ -0,0 +1,29 @@+from voxshift.audio.cable import find_cables+++def dev(name, i, o):+ return {"name": name, "max_input_channels": i, "max_output_channels": o}+++def test_detects_pairs_and_prefers_vbcable():+ devices = [+ dev("Speakers (Realtek(R) Audio)", 0, 2),+ dev("VoiceMeeter Input (VB-Audio VoiceMeeter VAIO)", 0, 8),+ dev("VoiceMeeter Output (VB-Audio VoiceMeeter VAIO)", 8, 0),+ dev("CABLE Input (VB-Audio Virtual Cable)", 0, 8),+ dev("CABLE Output (VB-Audio Virtual Cable)", 8, 0),+ ]+ cables = find_cables(devices=devices)+ assert [c.label for c in cables] == ["VB-CABLE", "VoiceMeeter"]+ assert cables[0].playback == "CABLE Input (VB-Audio Virtual Cable)"+ assert cables[0].capture == "CABLE Output (VB-Audio Virtual Cable)"+++def test_half_a_cable_is_not_a_cable():+ # a capture endpoint without its playback side cannot carry our audio+ assert find_cables(devices=[dev("CABLE Output (VB-Audio Virtual Cable)", 8, 0)]) == []+++def test_cable_a_is_not_mistaken_for_cable():+ devices = [dev("CABLE-A Input (VB-Audio Cable A)", 0, 8), dev("CABLE-A Output (VB-Audio Cable A)", 8, 0)]+ assert [c.label for c in find_cables(devices=devices)] == ["VB-CABLE A"]diff --git a/tests/test_dsp.py b/tests/test_dsp.pynew file mode 100644index 0000000..82d6d1b--- /dev/null+++ b/tests/test_dsp.py@@ -0,0 +1,110 @@+import numpy as np+import pytest++from voxshift.dsp.graph import Voice+from voxshift.dsp.nodes import NODE_TYPES, Biquad, Delay, FormantPitchShifter, PitchShift+from voxshift.dsp.stft import StreamingSTFT+from voxshift.presets import is_ai, list_presets++SR = 48000+++def sine(f, secs=1.0, sr=SR):+ return 0.5 * np.sin(2 * np.pi * f * np.arange(int(sr * secs)) / sr)+++def run(node, x, block):+ return np.concatenate([node.process(x[i:i + block]) for i in range(0, len(x), block)])+++def dominant_hz(y, sr=SR):+ y = y[len(y) // 3:] # skip warm-up+ spec = np.abs(np.fft.rfft(y * np.hanning(len(y))))+ return np.argmax(spec) * sr / len(y)++[email protected]("block", [64, 300, 512, 2048])+def test_stft_identity_has_exact_latency(block):+ st = StreamingSTFT(2048, 512)+ x = np.random.default_rng(0).standard_normal(SR // 2)+ y = run(st, x, block)+ lat = st.latency+ assert len(y) == len(x)+ np.testing.assert_allclose(y[lat + 2048:], x[2048: len(x) - lat], atol=1e-9)+++def test_formant_pitch_shifter_octave_up():+ node = FormantPitchShifter(SR, semitones=12, preserve_formants=False)+ assert abs(dominant_hz(run(node, sine(220), 512)) - 440) < 15+++def test_granular_pitch_shift_fifth_down():+ node = PitchShift(SR, semitones=-7)+ target = 330 * 2 ** (-7 / 12)+ assert abs(dominant_hz(run(node, sine(330), 480)) - target) < 10+++def test_autotune_snaps_to_semitone():+ f_in = 440 * 2 ** (0.4 / 12) # 40 cents sharp of A4+ node = FormantPitchShifter(SR, autotune=1.0, autotune_speed=1.0, preserve_formants=False)+ assert abs(dominant_hz(run(node, sine(f_in, 1.5), 512)) - 440) < 8++[email protected]("block_a,block_b", [(512, 173), (64, 1000)])+def test_time_domain_nodes_are_block_size_invariant(block_a, block_b):+ x = np.random.default_rng(1).standard_normal(SR // 4)+ for make in (lambda: Biquad(SR, kind="peaking", freq=1000, q=2, gain_db=6),+ lambda: Delay(SR, time_ms=7, feedback=0.6, mix=0.5)):+ np.testing.assert_allclose(run(make(), x, block_a), run(make(), x, block_b), atol=1e-9)+++DSP_PRESETS = {k: v for k, v in list_presets().items() if not is_ai(v)}++[email protected]("key", sorted(DSP_PRESETS))+def test_every_dsp_preset_is_stable(key):+ v = Voice(DSP_PRESETS[key], SR)+ rng = np.random.default_rng(2)+ x = np.concatenate([sine(180, 0.5), 0.1 * rng.standard_normal(SR // 2)])+ y = run(v, x, 480)+ assert y.shape == x.shape+ assert np.all(np.isfinite(y))+ assert np.max(np.abs(y)) < 8.0+++def test_node_registry_covers_presets():+ used = set()++ def walk(chain):+ for item in chain:+ if item["type"] == "Parallel":+ for b in item["branches"]:+ walk(b)+ else:+ used.add(item["type"])+ for spec in DSP_PRESETS.values():+ walk(spec["chain"])+ assert used <= set(NODE_TYPES)+++def test_parallel_branches_are_latency_aligned():+ spec = {"chain": [{"type": "Parallel", "branches": [+ [{"type": "FormantPitchShifter", "params": {"semitones": 0, "preserve_formants": False}}],+ [{"type": "Gain", "params": {"gain_db": 0}}]]}]}+ v = Voice(spec, SR)+ assert v.latency == 2048+++def test_partitioned_reverb_matches_direct_convolution():+ from scipy.signal import fftconvolve++ from voxshift.dsp.nodes import ConvolutionReverb+ node = ConvolutionReverb(SR, decay_s=0.3, predelay_ms=30, mix=1.0)+ x = np.random.default_rng(3).standard_normal(SR // 2)+ y = run(node, x, 300)+ # rebuild the effective IR: partition delay P + shortened pre-delay+ pre = int(SR * 0.03) - node.P+ parts = np.fft.irfft(node.H, axis=1)[:, : node.P].ravel()+ ref = fftconvolve(x, np.concatenate([np.zeros(node.P), parts]))[: len(x)]+ assert pre > 0+ np.testing.assert_allclose(y, ref, atol=1e-8)diff --git a/tests/test_engine.py b/tests/test_engine.pynew file mode 100644index 0000000..57b60e8--- /dev/null+++ b/tests/test_engine.py@@ -0,0 +1,46 @@+"""Audio-engine callback logic, driven directly (no audio device is opened)."""+import numpy as np+import pytest++from voxshift.presets import build_processor, load_spec++SR = 48000+++def engine():+ try:+ from voxshift.audio.engine import AudioEngine+ return AudioEngine(samplerate=SR, blocksize=480)+ except Exception as e: # no PortAudio devices on this machine+ pytest.skip(f"no audio devices: {e}")+++def call(engine, x, out_ch=2):+ out = np.zeros((len(x), out_ch), np.float32)+ engine._callback(x[:, None].astype(np.float32), out, len(x), None, None)+ return out+++def test_bypass_is_transparent_below_limiter(engine):+ engine.voice_enabled = False+ x = 0.1 * np.sin(2 * np.pi * 300 * np.arange(480) / SR)+ out = call(engine, x)+ np.testing.assert_allclose(out[:, 0], out[:, 1])+ assert np.max(np.abs(out[:, 0] - x)) < 1e-3 # tanh limiter is ~linear at -20 dBFS+++def test_limiter_caps_hot_signal(engine):+ engine.set_processor(build_processor(load_spec("megaphone"), SR))+ engine.output_gain_db = 24+ out = call(engine, np.random.default_rng(0).standard_normal(480))+ assert np.max(np.abs(out)) <= 10 ** (-0.5 / 20) + 1e-6+++def test_soundboard_mixes_and_drains(engine):+ engine.voice_enabled = False+ engine.play_sound(np.full(24000, 0.25), 24000) # 1 s at 24 kHz -> 48000 samples+ blocks = [call(engine, np.zeros(480))[:, 0] for _ in range(101)]+ assert np.mean(np.abs(blocks[0])) > 0.2+ assert np.max(np.abs(blocks[-1])) == 0.0+ assert engine._sounds == []diff --git a/tests/test_features.py b/tests/test_features.pynew file mode 100644index 0000000..c1b25ec--- /dev/null+++ b/tests/test_features.py@@ -0,0 +1,53 @@+"""numpy front-ends vs the torch / transformers implementations they replace."""+import numpy as np+import pytest++torch = pytest.importorskip("torch")+transformers = pytest.importorskip("transformers")++from voxshift.ai import features as F # noqa: E402+from voxshift.ai.seedvc import _seedvc_imports # noqa: E402++[email protected](scope="module")+def consts():+ fe = transformers.WhisperFeatureExtractor() # whisper-small front-end defaults+ return fe, F.build_constants(fe.mel_filters, 22050, 1024, 80, 0, None)+++def audio(n, seed=0):+ rng = np.random.default_rng(seed)+ t = np.arange(n) / 16000+ return (0.3 * np.sin(2 * np.pi * 220 * t) + 0.05 * rng.standard_normal(n)).astype(np.float32)+++def test_whisper_log_mel(consts):+ fe, c = consts+ x = audio(16000 * 4)+ ref = fe([x], return_tensors="np", sampling_rate=16000).input_features+ got = F.whisper_log_mel(x, c["whisper_mel_filters"])+ assert got.shape == ref.shape == (1, 80, 3000)+ np.testing.assert_allclose(got, ref, atol=2e-5)+++def test_seedvc_mel(consts):+ _, c = consts+ with _seedvc_imports():+ from modules.audio import mel_spectrogram+ x = audio(22050 * 2, 1)+ ref = mel_spectrogram(torch.from_numpy(x)[None], n_fft=1024, num_mels=80, sampling_rate=22050, hop_size=256,+ win_size=1024, fmin=0, fmax=None, center=False).numpy()+ got = F.mel_spectrogram(x, c["mel_basis"])+ assert got.shape == ref.shape+ np.testing.assert_allclose(got, ref, atol=1e-4)+++def test_kaldi_fbank(consts):+ import torchaudio+ _, c = consts+ x = audio(16000 * 3, 2)+ ref = torchaudio.compliance.kaldi.fbank(torch.from_numpy(x)[None], num_mel_bins=80, dither=0,+ sample_frequency=16000).numpy()+ got = F.kaldi_fbank(x, c["kaldi_mel_banks"])+ assert got.shape == ref.shape+ np.testing.assert_allclose(got, ref, atol=1e-3)diff --git a/tests/test_onnx_parity.py b/tests/test_onnx_parity.pynew file mode 100644index 0000000..6b30b55--- /dev/null+++ b/tests/test_onnx_parity.py@@ -0,0 +1,59 @@+"""ONNX Runtime vs PyTorch parity for every exported Seed-VC network.++Integration test: needs the Seed-VC weights and `python -m voxshift export-onnx`.+"""+import numpy as np+import pytest++from voxshift.ai.seedvc import REPO_ROOT++ONNX_DIR = REPO_ROOT / "models" / "onnx" / "whisper-small-bigvgan"+pytestmark = pytest.mark.skipif(not (ONNX_DIR / "config.json").is_file(), reason="run export-onnx first")++[email protected](scope="module", params=["CPUExecutionProvider", "DmlExecutionProvider"])+def pair(request):+ import onnxruntime as ort+ if request.param not in ort.get_available_providers():+ pytest.skip(f"{request.param} unavailable")+ from voxshift.ai.onnx_backend import OnnxSeedVCModel+ from voxshift.ai.seedvc import SeedVCModel+ return SeedVCModel.get("whisper-small-bigvgan", device="cpu", fp16=False), \+ OnnxSeedVCModel(str(ONNX_DIR), [request.param])+++def rel_err(a, b):+ a, b = np.asarray(a, np.float64), np.asarray(b, np.float64)+ return float(np.linalg.norm(a - b) / (np.linalg.norm(b) + 1e-12))+++def test_networks_match(pair):+ import torch+ tm, om = pair+ g = torch.Generator().manual_seed(0)+ with torch.no_grad():+ w16 = torch.randn(1, 16000 * 3, generator=g) * 0.1+ fp16 = om.cfg.get("precision", {})+ tol = lambda net: 3e-2 if fp16.get(net) == "fp16" else 1e-2 # noqa: E731+ assert rel_err(om.content(w16[0].numpy()), tm.semantic_fn(w16)) < tol("whisper_encoder")++ s = torch.randn(1, 120, 768, generator=g)+ yl = torch.LongTensor([240])+ assert rel_err(om.length_regulator(s.numpy(), 240),+ tm.model.length_regulator(s, ylens=yl, n_quantizers=3, f0=None)[0]) < 1e-3++ for frames in (120, 257, 300, 451): # include partial pooling segments+ fb = torch.randn(1, frames, 80, generator=g)+ assert rel_err(om._run("campplus", fbank=fb.numpy()), tm.campplus(fb)) < 1e-3, frames++ mel = torch.randn(1, 80, 64, generator=g)+ assert rel_err(om.vocoder(mel.numpy()), tm.vocoder(mel).reshape(-1)) < tol("vocoder")++ T = 200+ est = tm.model.cfm.estimator+ args = (torch.randn(2, 80, T, generator=g), torch.randn(2, 80, T, generator=g), torch.rand(2, generator=g),+ torch.randn(2, 192, generator=g), torch.randn(2, T, 512, generator=g))+ ref = est(args[0], args[1], torch.LongTensor([T]), args[2], args[3], args[4])+ got = om._run("dit_step", x=args[0].numpy(), prompt_x=args[1].numpy(), t=args[2].numpy(),+ style=args[3].numpy(), mu=args[4].numpy())+ assert rel_err(got, ref) < tol("dit_step")diff --git a/third_party/seed-vc b/third_party/seed-vcnew file mode 160000index 0000000..51383ef--- /dev/null+++ b/third_party/seed-vc@@ -0,0 +1 @@+Subproject commit 51383efd921027683c89e5348211d93ff12ac2a8diff --git a/voxshift/__init__.py b/voxshift/__init__.pynew file mode 100644index 0000000..c7188fd--- /dev/null+++ b/voxshift/__init__.py@@ -0,0 +1,2 @@+"""VoxShift — local real-time voice changer."""+__version__ = "0.2.0"diff --git a/voxshift/__main__.py b/voxshift/__main__.pynew file mode 100644index 0000000..4e28416--- /dev/null+++ b/voxshift/__main__.py@@ -0,0 +1,3 @@+from .cli import main++main()diff --git a/voxshift/ai/__init__.py b/voxshift/ai/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/voxshift/ai/features.py b/voxshift/ai/features.pynew file mode 100644index 0000000..617e1c5--- /dev/null+++ b/voxshift/ai/features.py@@ -0,0 +1,88 @@+"""Torch-free audio front-ends for the ONNX runtime path.++The standalone build computes these in numpy so it needs only numpy,+scipy and ONNX Runtime (no PyTorch / transformers / librosa). Each function reproduces its reference+implementation (tested against them in tests/test_features.py):++* :func:`whisper_log_mel` — Hugging Face ``WhisperFeatureExtractor``+* :func:`mel_spectrogram` — Seed-VC ``modules.audio.mel_spectrogram``+* :func:`kaldi_fbank` — ``torchaudio.compliance.kaldi.fbank`` (CAMPPlus input)++Filter matrices are produced once at export time (``features.npz``).+"""+from __future__ import annotations++import math++import numpy as np+from numpy.lib.stride_tricks import sliding_window_view+from scipy.signal import resample_poly+++def resample(x: np.ndarray, sr_in: int, sr_out: int) -> np.ndarray:+ if sr_in == sr_out:+ return x+ g = math.gcd(int(sr_in), int(sr_out))+ return resample_poly(x, sr_out // g, sr_in // g).astype(np.float32)+++def _frames(x: np.ndarray, size: int, hop: int) -> np.ndarray:+ return sliding_window_view(x, size)[::hop]+++def whisper_log_mel(w16: np.ndarray, mel_filters: np.ndarray, n_samples: int = 480000,+ n_fft: int = 400, hop: int = 160) -> np.ndarray:+ """[N] float audio @16 kHz -> [1, 80, 3000] Whisper input features."""+ x = np.zeros(n_samples, dtype=np.float64)+ x[: min(len(w16), n_samples)] = w16[:n_samples]+ x = np.pad(x, n_fft // 2, mode="reflect")+ win = np.hanning(n_fft + 1)[:-1]+ spec = np.abs(np.fft.rfft(_frames(x, n_fft, hop) * win, axis=-1)) ** 2 # [frames, 201]+ mel = np.maximum(spec @ mel_filters, 1e-10) # [frames, 80]+ log_spec = np.log10(mel).T[:, :-1]+ log_spec = np.maximum(log_spec, log_spec.max() - 8.0)+ return ((log_spec + 4.0) / 4.0)[None].astype(np.float32)+++def mel_spectrogram(wav: np.ndarray, mel_basis: np.ndarray, n_fft: int = 1024, hop: int = 256,+ win_size: int = 1024) -> np.ndarray:+ """[N] float audio @ model rate -> [1, n_mels, frames] log-mel (Seed-VC, center=False)."""+ pad = (n_fft - hop) // 2+ x = np.pad(wav.astype(np.float64), pad, mode="reflect")+ win = np.hanning(win_size + 1)[:-1]+ if win_size < n_fft:+ lpad = (n_fft - win_size) // 2+ win = np.pad(win, (lpad, n_fft - win_size - lpad))+ spec = np.fft.rfft(_frames(x, n_fft, hop) * win, axis=-1)+ mag = np.sqrt(spec.real**2 + spec.imag**2 + 1e-9) # [frames, bins]+ mel = mel_basis @ mag.T # [n_mels, frames]+ return np.log(np.maximum(mel, 1e-5))[None].astype(np.float32)+++def build_constants(whisper_mel_filters: np.ndarray, sr: int, n_fft: int, n_mels: int, fmin: float,+ fmax: float | None) -> dict[str, np.ndarray]:+ """Dev/export-time only (needs librosa + torchaudio): the filter matrices+ the runtime functions above consume."""+ import librosa+ from torchaudio.compliance.kaldi import get_mel_banks+ banks, _ = get_mel_banks(80, 512, 16000.0, 20.0, 0.0, 100.0, -500.0, 1.0)+ return {+ "whisper_mel_filters": np.asarray(whisper_mel_filters, np.float64), # [201, 80]+ "mel_basis": librosa.filters.mel(sr=sr, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax),+ "kaldi_mel_banks": np.pad(banks.numpy().astype(np.float64), ((0, 0), (0, 1))), # [80, 257]+ }+++def kaldi_fbank(w16: np.ndarray, mel_banks: np.ndarray, frame_len: int = 400, shift: int = 160,+ preemph: float = 0.97) -> np.ndarray:+ """[N] float audio @16 kHz -> [frames, n_mels] log mel filterbank (Kaldi defaults,+ povey window, dither 0, snip_edges, power spectrum)."""+ fr = _frames(w16.astype(np.float64), frame_len, shift).copy()+ fr -= fr.mean(axis=1, keepdims=True) # remove DC offset+ prev = np.concatenate([fr[:, :1], fr[:, :-1]], axis=1) # replicate-pad preemphasis+ fr = fr - preemph * prev+ fr *= np.hanning(frame_len) ** 0.85 # povey window+ n_fft = 1 << (frame_len - 1).bit_length()+ power = np.abs(np.fft.rfft(fr, n=n_fft, axis=-1)) ** 2 # [frames, n_fft/2+1]+ eps = np.finfo(np.float32).eps+ return np.log(np.maximum(power @ mel_banks.T, eps)).astype(np.float32)diff --git a/voxshift/ai/onnx_backend.py b/voxshift/ai/onnx_backend.pynew file mode 100644index 0000000..6f28525--- /dev/null+++ b/voxshift/ai/onnx_backend.py@@ -0,0 +1,198 @@+"""ONNX Runtime backend for the Seed-VC pipeline — numpy only.++Runs the networks exported by ``onnx_export.py`` through ONNX Runtime with+DirectML first (any DirectX 12 GPU), then CUDA, then CPU. The Euler/CFG+loop, resampling and audio front-ends run in numpy (``features.py``), so a+standalone build needs no PyTorch.+"""+from __future__ import annotations++import json+from pathlib import Path++import numpy as np++from . import features as F+from ..paths import install_dir++PROVIDER_PREFERENCE = ["DmlExecutionProvider", "CUDAExecutionProvider", "CPUExecutionProvider"]+NETWORKS = ("whisper_encoder", "length_regulator", "dit_step", "campplus", "vocoder")+++def make_session(path: Path, providers: list[str] | None = None):+ import onnxruntime as ort+ avail = ort.get_available_providers()+ chosen = [p for p in (providers or PROVIDER_PREFERENCE) if p in avail] or ["CPUExecutionProvider"]+ so = ort.SessionOptions()+ so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL+ so.log_severity_level = 3+ if "DmlExecutionProvider" in chosen: # DML requires these two settings+ so.enable_mem_pattern = False+ so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL+ return ort.InferenceSession(str(path), sess_options=so, providers=chosen)+++class OnnxSeedVCModel:+ _cache: dict[tuple, "OnnxSeedVCModel"] = {}++ @classmethod+ def get(cls, onnx_dir: str, providers: list[str] | None = None) -> "OnnxSeedVCModel":+ key = (str(onnx_dir), tuple(providers or ()))+ if key not in cls._cache:+ cls._cache[key] = cls(onnx_dir, providers)+ return cls._cache[key]++ def __init__(self, onnx_dir: str, providers: list[str] | None = None):+ d = Path(onnx_dir)+ if not d.is_absolute(): # "models/onnx/<name>" relative to the install / repo root+ d = install_dir() / d+ if not (d / "config.json").is_file():+ raise FileNotFoundError(f"{d} has no exported model; run `python -m voxshift export-onnx` first")+ self.dir = d+ self.cfg = json.loads((d / "config.json").read_text())+ self.sr, self.hop = self.cfg["sr"], self.cfg["hop_length"]+ self.sess = {n: make_session(d / f"{n}.onnx", providers) for n in NETWORKS}+ self.providers = self.sess["dit_step"].get_providers()+ c = np.load(d / "features.npz")+ self.whisper_filters, self.mel_basis, self.kaldi_banks = (+ c["whisper_mel_filters"], c["mel_basis"], c["kaldi_mel_banks"])+ self.rng = np.random.default_rng()++ def _run(self, name, **feeds):+ feeds = {k: np.ascontiguousarray(v, dtype=np.int64 if v.dtype.kind in "iu" else np.float32)+ for k, v in feeds.items()}+ return self.sess[name].run(None, feeds)[0]++ # -- building blocks (all numpy) ------------------------------------+ def content(self, w16: np.ndarray) -> np.ndarray:+ """16 kHz audio -> Whisper encoder states [1, frames, 768] (50 frames/s)."""+ hidden = self._run("whisper_encoder", input_features=F.whisper_log_mel(w16, self.whisper_filters))+ return hidden[:, : len(w16) // 320 + 1]++ def length_regulator(self, content: np.ndarray, frames: int) -> np.ndarray:+ return self._run("length_regulator", content=content, ylens=np.array([frames]))++ def style(self, w16: np.ndarray) -> np.ndarray:+ fb = F.kaldi_fbank(w16, self.kaldi_banks)+ return self._run("campplus", fbank=(fb - fb.mean(axis=0, keepdims=True))[None])++ def mel(self, wav: np.ndarray) -> np.ndarray:+ return F.mel_spectrogram(wav, self.mel_basis, self.cfg["n_fft"], self.hop, self.cfg["win_length"])++ def vocoder(self, mel: np.ndarray) -> np.ndarray:+ return self._run("vocoder", mel=mel).reshape(-1)++ def cfm(self, mu, prompt, style, n_timesteps: int, cfg_rate: float) -> np.ndarray:+ """Seed-VC ``BASECFM.solve_euler`` with the DiT estimator in ORT."""+ B, T = mu.shape[0], mu.shape[1]+ x = self.rng.standard_normal((B, 80, T)).astype(np.float32)+ P = prompt.shape[-1]+ prompt_x = np.zeros_like(x)+ prompt_x[..., :P] = prompt[..., :P]+ x[..., :P] = 0+ t_span = np.linspace(0, 1, n_timesteps + 1, dtype=np.float32)+ if cfg_rate > 0:+ pz, sz, mz = (np.concatenate([a, np.zeros_like(a)]) for a in (prompt_x, style, mu))+ for step in range(1, len(t_span)):+ t, dt = t_span[step - 1], t_span[step] - t_span[step - 1]+ if cfg_rate > 0:+ d = self._run("dit_step", x=np.concatenate([x, x]), prompt_x=pz, t=np.array([t, t]), style=sz, mu=mz)+ d = (1 + cfg_rate) * d[:B] - cfg_rate * d[B:]+ else:+ d = self._run("dit_step", x=x, prompt_x=prompt_x, t=np.array([t]), style=style, mu=mu)+ x = x + dt * d+ x[..., :P] = 0+ return x+++def load_audio(path: str, sr: int) -> np.ndarray:+ import soundfile as sf+ data, file_sr = sf.read(path, dtype="float32", always_2d=True)+ return F.resample(data.mean(axis=1), file_sr, sr)+++class NumpyStreamer:+ """numpy port of :class:`voxshift.ai.seedvc.SeedVCStreamer` (same context+ windows, skip head/tail and SOLA crossfade) driving :class:`OnnxSeedVCModel`."""++ def __init__(self, model: OnnxSeedVCModel, device_sr: int, cfg):+ if cfg.extra_time_ce < cfg.extra_time:+ raise ValueError("extra_time_ce must be >= extra_time")+ self.m, self.cfg, self.sr = model, cfg, device_sr+ zc = self.zc = device_sr // 50+ q = lambda s: int(round(s * device_sr / zc)) * zc # noqa: E731+ self.block_frame = q(cfg.block_time)+ self.block_frame_16k = 320 * self.block_frame // zc+ crossfade = q(cfg.crossfade_time)+ self.sola_buffer_frame = min(crossfade, 4 * zc)+ self.sola_search_frame = zc+ self.extra_frame = q(cfg.extra_time_ce)+ self.extra_frame_right = max(zc, q(cfg.extra_time_right))+ total = self.extra_frame + crossfade + self.sola_search_frame + self.block_frame + self.extra_frame_right+ self.input_wav = np.zeros(total, np.float32)+ self.input_wav_res = np.zeros(320 * total // zc, np.float32)+ self.sola_buffer = np.zeros(self.sola_buffer_frame, np.float32)+ self.skip_head = self.extra_frame // zc+ self.skip_tail = self.extra_frame_right // zc+ self.return_length = (self.block_frame + self.sola_buffer_frame + self.sola_search_frame) // zc+ self.fade_in = (np.sin(0.5 * np.pi * np.linspace(0, 1, self.sola_buffer_frame)) ** 2).astype(np.float32)+ self.fade_out = 1 - self.fade_in+ self.prompt = None+ self._prev_loud = False+ self.last_infer_ms = 0.0+ if cfg.reference:+ self.set_reference(cfg.reference)++ @property+ def latency(self) -> int:+ return self.extra_frame_right + self.sola_buffer_frame + self.sola_search_frame // 2++ def set_reference(self, path: str) -> None:+ m = self.m+ wav = load_audio(path, m.sr)[: int(m.sr * self.cfg.max_prompt_length)]+ w16 = F.resample(wav, m.sr, 16000)+ mel = m.mel(wav)+ cond = m.length_regulator(m.content(w16), mel.shape[2])+ self.prompt = (cond, mel, m.style(w16))+ self.cfg.reference = path++ def _infer(self) -> np.ndarray:+ m, cfg = self.m, self.cfg+ cond_p, mel_p, style = self.prompt+ ce_dit = int((cfg.extra_time_ce - cfg.extra_time) * 50) # content-encoder vs DiT context gap+ s_alt = m.content(self.input_wav_res)[:, ce_dit:]+ frames = int((self.skip_head + self.return_length + self.skip_tail - ce_dit) / 50 * m.sr // m.hop)+ cat = np.concatenate([cond_p, m.length_regulator(s_alt, frames)], axis=1)+ mel = m.cfm(cat, mel_p, style, cfg.diffusion_steps, cfg.inference_cfg_rate)[:, :, mel_p.shape[-1]:]+ wave = m.vocoder(mel)+ out_len, tail = self.return_length * m.sr // 50, self.skip_tail * m.sr // 50+ wave = F.resample(wave[-out_len - tail: -tail], m.sr, self.sr)+ need = self.return_length * self.zc+ return np.pad(wave, (0, max(0, need - len(wave))))[:need]++ def process_block(self, block: np.ndarray) -> np.ndarray:+ import time+ if self.prompt is None:+ raise RuntimeError("no reference voice set; call set_reference(path)")+ n = self.block_frame+ assert len(block) == n, (len(block), n)+ self.input_wav = np.roll(self.input_wav, -n)+ self.input_wav[-n:] = block+ self.input_wav_res = np.roll(self.input_wav_res, -self.block_frame_16k)+ self.input_wav_res[-320 * (n // self.zc + 1):] = F.resample(+ self.input_wav[-n - 2 * self.zc:], self.sr, 16000)[320:]+ loud = 20 * np.log10(float(np.sqrt(np.mean(block**2))) + 1e-9) > self.cfg.silence_threshold_db+ t0 = time.perf_counter()+ infer = self._infer() if (loud or self._prev_loud) else np.zeros(self.return_length * self.zc, np.float32)+ self._prev_loud = loud+ self.last_infer_ms = (time.perf_counter() - t0) * 1000+ # SOLA: best-aligned offset by normalised cross-correlation, then crossfade+ sb, ss = self.sola_buffer_frame, self.sola_search_frame+ conv_in = infer[: sb + ss]+ num = np.correlate(conv_in, self.sola_buffer, "valid")+ den = np.sqrt(np.convolve(conv_in**2, np.ones(sb), "valid") + 1e-8)+ off = int(np.argmax(num / den))+ infer = infer[off:].copy()+ infer[:sb] = infer[:sb] * self.fade_in + self.sola_buffer * self.fade_out+ self.sola_buffer[:] = infer[n: n + sb]+ return infer[:n].astype(np.float64)diff --git a/voxshift/ai/onnx_export.py b/voxshift/ai/onnx_export.pynew file mode 100644index 0000000..71c3ef3--- /dev/null+++ b/voxshift/ai/onnx_export.py@@ -0,0 +1,235 @@+"""Export the Seed-VC networks to ONNX (``voxshift export-onnx``).++Splits the open Seed-VC Whisper-small + BigVGAN checkpoint into networks+that ONNX Runtime can run without PyTorch:++ whisper_encoder.onnx log-mel [1,80,3000] -> hidden [1,1500,768]+ length_regulator.onnx hidden [1,S,768], ylens [1] -> cond [1,T,512]+ dit_step.onnx x, prompt_x [B,80,T], t [B],+ style [B,192], mu [B,T,512] -> dphi/dt [B,80,T]+ campplus.onnx fbank [1,F,80] -> style [1,192]+ vocoder.onnx mel [1,80,T] -> wave [1,1,T*hop]+ config.json sample rates, hop, Whisper front-end settings++The Euler loop, CFG mix, resampling and feature extraction stay in the host+(``onnx_backend.py``).+"""+from __future__ import annotations++import contextlib+import json+from pathlib import Path++import numpy as np+import torch+from torch import nn++from .seedvc import SeedVCModel+++class _WhisperEncoder(nn.Module):+ def __init__(self, enc):+ super().__init__()+ self.enc = enc++ def forward(self, feats):+ return self.enc(feats, return_dict=True).last_hidden_state+++class _LengthRegulator(nn.Module):+ def __init__(self, lr):+ super().__init__()+ self.lr = lr++ def forward(self, x, ylens):+ return self.lr(x, ylens=ylens, n_quantizers=3, f0=None)[0]+++class _DiTStep(nn.Module):+ def __init__(self, est):+ super().__init__()+ self.est = est++ def forward(self, x, prompt_x, t, style, mu):+ # `sequence_mask` builds `arange(length.max())`, which the tracer freezes+ # at the export length. Streaming never pads, so derive an all-ones mask+ # from x's (dynamic) shape instead.+ # Likewise SConv1d's `get_extra_padding_for_conv1d` runs math.ceil() on+ # the traced length (freezing `extra = export_len - T`); for stride-1+ # convs (all of the WaveNet head) the extra padding is exactly 0.+ import torch.nn.functional as F+ from modules import diffusion_transformer as dtm+ from modules import encodec+ extra = int(self.est.style_as_token) + int(self.est.time_as_token)+ row = F.pad(torch.ones_like(x[:1, 0, :]), (extra, 0), value=1.0) > 0+ saved_mask, saved_pad = dtm.sequence_mask, encodec.get_extra_padding_for_conv1d+ dtm.sequence_mask = lambda length, max_length=None: row+ encodec.get_extra_padding_for_conv1d = (+ lambda xx, k, s, p=0: 0 if s == 1 else saved_pad(xx, k, s, p))+ try:+ return self.est(x, prompt_x, torch.zeros(1, dtype=torch.long), t, style, mu)+ finally:+ dtm.sequence_mask, encodec.get_extra_padding_for_conv1d = saved_mask, saved_pad+++class _Vocoder(nn.Module):+ def __init__(self, voc):+ super().__init__()+ self.voc = voc++ def forward(self, mel):+ return self.voc(mel)+++def _exportable_bigvgan():+ """BigVGAN's anti-aliased resamplers apply one filter to every channel via+ ``filter.expand(C, -1, -1)`` with C read from the traced input shape, so+ the exporter sees a depthwise kernel of unknown shape. The channel count+ is fixed by the architecture; pinning it as a Python int yields a+ constant ``[C, 1, K]`` kernel and an ordinary grouped (depthwise) conv,+ which every execution provider runs efficiently."""+ import torch.nn.functional as F+ from modules.bigvgan.alias_free_activation.torch import filter as filt+ from modules.bigvgan.alias_free_activation.torch import resample++ def up(self, x):+ C = int(x.shape[1])+ x = F.pad(x, (self.pad, self.pad), mode="replicate")+ w = self.filter.expand(C, -1, -1).contiguous()+ y = self.ratio * F.conv_transpose1d(x, w, stride=self.stride, groups=C)+ return y[..., self.pad_left: -self.pad_right]++ def lowpass(self, x):+ C = int(x.shape[1])+ if self.padding:+ x = F.pad(x, (self.pad_left, self.pad_right), mode=self.padding_mode)+ return F.conv1d(x, self.filter.expand(C, -1, -1).contiguous(), stride=self.stride, groups=C)++ saved = resample.UpSample1d.forward, filt.LowPassFilter1d.forward+ resample.UpSample1d.forward, filt.LowPassFilter1d.forward = up, lowpass+ try:+ yield+ finally:+ resample.UpSample1d.forward, filt.LowPassFilter1d.forward = saved+++def _exportable_campplus():+ """CAMPPlus ``seg_pooling`` uses ``avg_pool1d(ceil_mode=True)``; PyTorch+ averages a trailing partial window over its valid samples only, which the+ exported graph does not reproduce for lengths that are not multiples of+ the segment. Re-express it as pad + reshape + sum / valid-count."""+ import torch.nn.functional as F+ from modules.campplus import layers++ def seg_pooling(self, x, seg_len=100, stype="avg"):+ B, C, T = x.shape+ n = (T + seg_len - 1) // seg_len+ xp = F.pad(x, (0, n * seg_len - T))+ blocks = xp.reshape(B, C, n, seg_len)+ if stype == "avg":+ counts = torch.clamp(T - torch.arange(n, device=x.device) * seg_len, max=seg_len).to(x.dtype)+ seg = blocks.sum(-1) / counts+ else:+ seg = blocks.amax(-1)+ return seg.unsqueeze(-1).expand(B, C, n, seg_len).reshape(B, C, n * seg_len)[..., :T]++ saved = layers.CAMLayer.seg_pooling+ layers.CAMLayer.seg_pooling = seg_pooling+ try:+ yield+ finally:+ layers.CAMLayer.seg_pooling = saved+++def _rel(a, b) -> float:+ """Relative L2 error; the rewrites only differ by float rounding (~1e-6)."""+ return float((a - b).norm() / (b.norm() + 1e-12))+++def _export(module, args, path, inputs, outputs, dynamic, opset):+ torch.onnx.export(module, args, str(path), input_names=inputs, output_names=outputs,+ dynamic_axes=dynamic, opset_version=opset, do_constant_folding=True, dynamo=False)+ print(f" wrote {path.name} ({path.stat().st_size / 2**20:.1f} MB)")+++def _to_fp16(path: Path) -> None:+ """Store weights/compute in fp16 but keep fp32 graph I/O, so the host+ code is precision-agnostic."""+ import onnx+ from onnxruntime.transformers.float16 import convert_float_to_float16+ model = onnx.load(str(path))+ model.graph.ClearField("value_info") # stale fp32 annotations break the converter's Cast handling+ model = convert_float_to_float16(model, keep_io_types=True)+ onnx.save(model, str(path))+ print(f" converted {path.name} to fp16 ({path.stat().st_size / 2**20:.1f} MB)")+++def export(preset: str = "whisper-small-bigvgan", out_dir: str = "models/onnx", opset: int = 17,+ fp16: bool = True) -> Path:+ m = SeedVCModel.get(preset, device="cpu", fp16=False)+ if m.content_type != "whisper" or m.vocoder_type != "bigvgan":+ raise SystemExit("ONNX export supports the Whisper + BigVGAN model; "+ "HiFT's complex STFT/ISTFT has no ONNX lowering.")+ out = Path(out_dir).resolve() / preset+ out.mkdir(parents=True, exist_ok=True)+ print(f"exporting {preset} -> {out}")+ fe = m.whisper_fe+ T, S = 300, 150+ with torch.no_grad():+ enc = m.whisper.encoder.float().eval()+ _export(_WhisperEncoder(enc), (torch.randn(1, 80, fe.nb_max_frames),), out / "whisper_encoder.onnx",+ ["input_features"], ["hidden"], None, opset)+ _export(_LengthRegulator(m.model.length_regulator), (torch.randn(1, S, 768), torch.LongTensor([T])),+ out / "length_regulator.onnx", ["content", "ylens"], ["cond"],+ {"content": {1: "S"}, "cond": {1: "T"}}, opset)+ est = m.model.cfm.estimator+ dit_args = (torch.randn(2, 80, T), torch.randn(2, 80, T), torch.rand(2), torch.randn(2, 192),+ torch.randn(2, T, 512))+ # The DiT adds python bools to a tensor (`x_lens + self.style_as_token`),+ # which the TorchScript tracer cannot type; ints behave identically.+ flags = {k: getattr(est, k) for k in ("style_as_token", "time_as_token")}+ for k, v in flags.items():+ setattr(est, k, int(v))+ try:+ _export(_DiTStep(est), dit_args, out / "dit_step.onnx", ["x", "prompt_x", "t", "style", "mu"],+ ["dphi"], {"x": {0: "B", 2: "T"}, "prompt_x": {0: "B", 2: "T"}, "t": {0: "B"},+ "style": {0: "B"}, "mu": {0: "B", 1: "T"}, "dphi": {0: "B", 2: "T"}}, opset)+ finally:+ for k, v in flags.items():+ setattr(est, k, v)+ with _exportable_campplus():+ fb = torch.randn(1, 257, 80)+ ref = m.campplus(fb)+ _export(m.campplus, (fb,), out / "campplus.onnx", ["fbank"], ["style"], {"fbank": {1: "F"}}, opset)+ assert _rel(ref, m.campplus(fb)) < 1e-4, "CAMPPlus rewrite changed the output"+ with _exportable_bigvgan():+ voc = _Vocoder(m.vocoder)+ mel = torch.randn(1, 80, 100)+ ref = voc(mel)+ _export(voc, (mel,), out / "vocoder.onnx", ["mel"], ["wave"], {"mel": {2: "T"}, "wave": {2: "N"}}, opset)+ assert _rel(ref, m.vocoder(mel)) < 1e-4, "BigVGAN rewrite changed the output"+ if fp16: # the transformer stacks dominate runtime; BigVGAN stays fp32 for its snake activations+ for name in ("whisper_encoder", "dit_step"):+ _to_fp16(out / f"{name}.onnx")+ sp = m.config["preprocess_params"]["spect_params"]+ cfg = {+ "model": preset,+ "sr": m.sr, "hop_length": m.hop, "n_fft": sp["n_fft"], "win_length": sp["win_length"],+ "n_mels": sp["n_mels"], "fmin": sp.get("fmin", 0), "fmax": sp.get("fmax", "None"),+ "content_encoder": "whisper", "whisper_name": m.config["model_params"]["speech_tokenizer"]["name"],+ "whisper_sr": 16000, "whisper_hop_length": fe.hop_length, "whisper_n_fft": fe.n_fft,+ "whisper_n_frames": fe.nb_max_frames, "vocoder": "bigvgan",+ "dit_extra_tokens": int(est.style_as_token) + int(est.time_as_token),+ "precision": {"whisper_encoder": "fp16" if fp16 else "fp32", "dit_step": "fp16" if fp16 else "fp32",+ "length_regulator": "fp32", "campplus": "fp32", "vocoder": "fp32"},+ }+ from .features import build_constants+ np.savez(out / "features.npz", **build_constants(fe.mel_filters, m.sr, sp["n_fft"], sp["n_mels"],+ sp.get("fmin", 0), None if sp.get("fmax", "None") == "None"+ else 8000))+ print(" wrote features.npz (Whisper / mel / Kaldi filter banks for the numpy front-ends)")+ (out / "config.json").write_text(json.dumps(cfg, indent=2))+ print(" wrote config.json")+ return outdiff --git a/voxshift/ai/seedvc.py b/voxshift/ai/seedvc.pynew file mode 100644index 0000000..bc4b3af--- /dev/null+++ b/voxshift/ai/seedvc.py@@ -0,0 +1,487 @@+"""AI voice conversion: Seed-VC v1 real-time pipeline, driven headlessly.++ mic @ device rate ──► 16 kHz ──► content encoder (Whisper-small | XLSR)+ ──► length regulator ──► DiT flow matching (N Euler steps,+ conditioned on the reference prompt mel + CAMPPlus style)+ ──► vocoder (BigVGAN | HiFT) ──► device rate ──► SOLA crossfade++The streaming arithmetic (context windows, skip head/tail, SOLA) is a port+of Seed-VC's ``real-time-gui.py`` with the GUI, FunASR VAD and globals+removed. Seed-VC is GPL-3.0; it is used as a git submodule.+"""+from __future__ import annotations++import contextlib+import io+import os+import queue+import sys+import threading+import time+from dataclasses import dataclass+from pathlib import Path++import numpy as np++REPO_ROOT = Path(__file__).resolve().parents[2]+SEEDVC_DIR = Path(os.environ.get("VOXSHIFT_SEEDVC", REPO_ROOT / "third_party" / "seed-vc"))++MODEL_PRESETS = {+ # name: (HF checkpoint, Seed-VC config)+ "whisper-small-bigvgan": ("DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth",+ "config_dit_mel_seed_uvit_whisper_small_wavenet.yml"),+ "xlsr-tiny-hifigan": ("DiT_uvit_tat_xlsr_ema.pth", "config_dit_mel_seed_uvit_xlsr_tiny.yml"),+}+++def _stub_dac():+ """Seed-VC imports ``dac.nn.quantize.VectorQuantize`` unconditionally but+ only instantiates it when ``vector_quantize: true`` (no shipped preset+ does). Installing descript-audio-codec drags in audiotools and a pinned+ protobuf, so register a stub when the real package is absent."""+ import importlib.util+ import types+ if "dac" in sys.modules or importlib.util.find_spec("dac") is not None:+ return++ class VectorQuantize: # noqa: D401 - placeholder+ def __init__(self, *a, **k):+ raise RuntimeError("this checkpoint needs `pip install descript-audio-codec`")++ pkg, nn, quant = (types.ModuleType(n) for n in ("dac", "dac.nn", "dac.nn.quantize"))+ quant.VectorQuantize = VectorQuantize+ pkg.nn, nn.quantize = nn, quant+ sys.modules.update({"dac": pkg, "dac.nn": nn, "dac.nn.quantize": quant})+++def _seedvc_imports():+ """Seed-VC resolves some files relative to its repo root."""+ if not (SEEDVC_DIR / "modules").is_dir():+ raise RuntimeError(+ f"Seed-VC not found at {SEEDVC_DIR}. Run `git submodule update --init` "+ "or set VOXSHIFT_SEEDVC.")+ if str(SEEDVC_DIR) not in sys.path:+ sys.path.insert(0, str(SEEDVC_DIR))+ _stub_dac()+ cwd = os.getcwd()+ os.chdir(SEEDVC_DIR)+ try:+ yield+ finally:+ os.chdir(cwd)+++class SeedVCModel:+ """Loads every network once; shareable between streamers."""++ _cache: dict[tuple, "SeedVCModel"] = {}++ @classmethod+ def get(cls, preset: str = "whisper-small-bigvgan", device: str | None = None,+ fp16: bool = True, checkpoint: str | None = None, config: str | None = None) -> "SeedVCModel":+ key = (preset, device, fp16, checkpoint, config)+ if key not in cls._cache:+ cls._cache[key] = cls(preset, device, fp16, checkpoint, config)+ return cls._cache[key]++ def __init__(self, preset, device, fp16, checkpoint, config):+ import torch+ import yaml+ from huggingface_hub import hf_hub_download++ self.torch = torch+ self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))+ self.fp16 = fp16 and self.device.type == "cuda"+ if checkpoint is None:+ ckpt_name, cfg_name = MODEL_PRESETS[preset]+ checkpoint = hf_hub_download("Plachta/Seed-VC", ckpt_name)+ config = hf_hub_download("Plachta/Seed-VC", cfg_name)+ cfg = yaml.safe_load(open(config, "r"))+ self.config = cfg++ with _seedvc_imports():+ import modules.flow_matching as fm+ from modules.commons import build_model, load_checkpoint, recursive_munch+ from modules.campplus.DTDNN import CAMPPlus+ from modules.audio import mel_spectrogram++ fm.tqdm = lambda it, *a, **k: it # no progress bar per streamed block++ mp = recursive_munch(cfg["model_params"])+ mp.dit_type = "DiT"+ model = build_model(mp, stage="DiT")+ model, *_ = load_checkpoint(model, None, checkpoint, load_only_params=True,+ ignore_modules=[], is_distributed=False)+ for k in model:+ model[k].eval().to(self.device)+ model.cfm.estimator.setup_caches(max_batch_size=1, max_seq_length=8192)+ self.model = model++ campplus_path = hf_hub_download("funasr/campplus", "campplus_cn_common.bin")+ self.campplus = CAMPPlus(feat_dim=80, embedding_size=192)+ self.campplus.load_state_dict(torch.load(campplus_path, map_location="cpu"))+ self.campplus.eval().to(self.device)++ self.vocoder_type = mp.vocoder.type+ self.vocoder = self._load_vocoder(mp, torch, yaml)+ self.content_type = mp.speech_tokenizer.type+ self.semantic_fn = self._load_content_encoder(mp, cfg, torch)++ sp = cfg["preprocess_params"]["spect_params"]+ self.sr = cfg["preprocess_params"]["sr"]+ self.hop = sp["hop_length"]+ mel_args = dict(n_fft=sp["n_fft"], win_size=sp["win_length"], hop_size=sp["hop_length"],+ num_mels=sp["n_mels"], sampling_rate=self.sr, fmin=sp.get("fmin", 0),+ fmax=None if sp.get("fmax", "None") == "None" else 8000, center=False)+ self.to_mel = lambda x: mel_spectrogram(x, **mel_args)++ def _load_vocoder(self, mp, torch, yaml):+ if mp.vocoder.type == "bigvgan":+ from modules.bigvgan import bigvgan+ voc = bigvgan.BigVGAN.from_pretrained(mp.vocoder.name, use_cuda_kernel=False)+ voc.remove_weight_norm()+ return voc.eval().to(self.device)+ if mp.vocoder.type == "hifigan":+ from huggingface_hub import hf_hub_download+ from modules.hifigan.f0_predictor import ConvRNNF0Predictor+ from modules.hifigan.generator import HiFTGenerator+ hcfg = yaml.safe_load(open(SEEDVC_DIR / "configs" / "hifigan.yml", "r"))+ gen = HiFTGenerator(**hcfg["hift"], f0_predictor=ConvRNNF0Predictor(**hcfg["f0_predictor"]))+ gen.load_state_dict(torch.load(hf_hub_download("FunAudioLLM/CosyVoice-300M", "hift.pt"),+ map_location="cpu"))+ return gen.eval().to(self.device)+ raise ValueError(f"unsupported vocoder {mp.vocoder.type!r} (bigvgan | hifigan)")++ def _load_content_encoder(self, mp, cfg, torch):+ dev = self.device+ if mp.speech_tokenizer.type == "whisper":+ from transformers import AutoFeatureExtractor, WhisperModel+ name = mp.speech_tokenizer.name+ wm = WhisperModel.from_pretrained(name, torch_dtype=torch.float16 if self.fp16 else torch.float32).to(dev)+ del wm.decoder+ fe = AutoFeatureExtractor.from_pretrained(name)+ self.whisper, self.whisper_fe = wm, fe++ def semantic_fn(w16):+ inp = fe([w16.squeeze(0).cpu().numpy()], return_tensors="pt", return_attention_mask=True,+ sampling_rate=16000)+ feats = wm._mask_input_features(inp.input_features, attention_mask=inp.attention_mask).to(dev)+ out = wm.encoder(feats.to(wm.encoder.dtype), head_mask=None, output_attentions=False,+ output_hidden_states=False, return_dict=True)+ return out.last_hidden_state.float()[:, : w16.size(-1) // 320 + 1]+ return semantic_fn+ if mp.speech_tokenizer.type == "xlsr":+ from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model+ name = cfg["model_params"]["speech_tokenizer"]["name"]+ layer = cfg["model_params"]["speech_tokenizer"]["output_layer"]+ fe = Wav2Vec2FeatureExtractor.from_pretrained(name)+ wm = Wav2Vec2Model.from_pretrained(name)+ wm.encoder.layers = wm.encoder.layers[:layer]+ wm = wm.to(dev).eval()+ if self.fp16:+ wm = wm.half()++ def semantic_fn(w16):+ inp = fe([w16[0].cpu().numpy()], return_tensors="pt", return_attention_mask=True,+ padding=True, sampling_rate=16000).to(dev)+ x = inp.input_values.half() if self.fp16 else inp.input_values+ return wm(x).last_hidden_state.float()+ return semantic_fn+ raise ValueError(f"unsupported content encoder {mp.speech_tokenizer.type!r}")+++class _GraphedSolver:+ """Captures the whole N-step Euler flow-matching solve as one CUDA graph.++ In streaming every DiT input has a fixed shape, so the ~30 small kernels+ per transformer layer per step can be replayed without Python or launch+ overhead. The only host sync in the DiT (``sequence_mask`` building an+ ``arange`` from a tensor length) is replaced by a static all-ones mask —+ valid because streaming never pads. Fresh noise is still drawn on every+ replay (PyTorch's CUDA RNG is graph-safe).+ """++ def __init__(self, model: SeedVCModel, mu, x_lens, prompt, style, steps: int, cfg_rate: float):+ import torch+ with _seedvc_imports():+ import modules.diffusion_transformer as dtm+ est = model.model.cfm.estimator+ seq_len = int(x_lens[0]) + int(est.style_as_token) + int(est.time_as_token)+ self.key = (tuple(mu.shape), tuple(prompt.shape), steps, cfg_rate)+ self.mu, self.prompt, self.style, self.x_lens = mu.clone(), prompt.clone(), style.clone(), x_lens.clone()+ fp16 = model.fp16++ def run():+ with torch.autocast("cuda", dtype=torch.float16 if fp16 else torch.float32, cache_enabled=False):+ return model.model.cfm.inference(self.mu, self.x_lens, self.prompt, self.style, None,+ n_timesteps=steps, inference_cfg_rate=cfg_rate)++ orig_mask = dtm.sequence_mask+ dtm.sequence_mask = lambda length, max_length=None: torch.ones(+ (length.shape[0], seq_len), dtype=torch.bool, device=length.device)+ try:+ side = torch.cuda.Stream()+ side.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(side):+ for _ in range(2):+ run()+ torch.cuda.current_stream().wait_stream(side)+ self.graph = torch.cuda.CUDAGraph()+ with torch.cuda.graph(self.graph):+ self.out = run()+ finally:+ dtm.sequence_mask = orig_mask++ def __call__(self, mu, prompt, style):+ self.mu.copy_(mu)+ self.prompt.copy_(prompt)+ self.style.copy_(style)+ self.graph.replay()+ return self.out.clone()+++@dataclass+class StreamConfig:+ reference: str = ""+ diffusion_steps: int = 8+ inference_cfg_rate: float = 0.7+ block_time: float = 0.30+ crossfade_time: float = 0.04+ extra_time_ce: float = 2.5 # content-encoder left context (s)+ extra_time: float = 0.5 # DiT left context (s); ce_dit gap = extra_time_ce - extra_time+ extra_time_right: float = 0.02 # right look-ahead (s)+ max_prompt_length: float = 3.0 # seconds of reference used as DiT prompt+ silence_threshold_db: float = -55.0+ cuda_graph: bool = True # replay the DiT solve as a CUDA graph++ @classmethod+ def from_spec(cls, spec: dict) -> "StreamConfig":+ names = cls.__dataclass_fields__+ return cls(**{k: v for k, v in spec.items() if k in names})+++class SeedVCStreamer:+ """Fixed-block streaming converter. Call :meth:`process_block` with exactly+ ``block_frame`` samples at ``device_sr``; it returns the same amount."""++ def __init__(self, model: SeedVCModel, device_sr: int, cfg: StreamConfig):+ import torch+ import torch.nn.functional as F+ import torchaudio.transforms as tat++ if cfg.extra_time_ce < cfg.extra_time:+ raise ValueError("extra_time_ce must be >= extra_time")+ self.torch, self.F = torch, F+ self.m, self.cfg, self.sr = model, cfg, device_sr+ dev = model.device+ zc = self.zc = device_sr // 50+ q = lambda s: int(round(s * device_sr / zc)) * zc # noqa: E731+ self.block_frame = q(cfg.block_time)+ self.block_frame_16k = 320 * self.block_frame // zc+ crossfade = q(cfg.crossfade_time)+ self.sola_buffer_frame = min(crossfade, 4 * zc)+ self.sola_search_frame = zc+ self.extra_frame = q(cfg.extra_time_ce)+ self.extra_frame_right = max(zc, q(cfg.extra_time_right))+ total = self.extra_frame + crossfade + self.sola_search_frame + self.block_frame + self.extra_frame_right+ self.input_wav = torch.zeros(total, device=dev)+ self.input_wav_res = torch.zeros(320 * total // zc, device=dev)+ self.sola_buffer = torch.zeros(self.sola_buffer_frame, device=dev)+ self.skip_head = self.extra_frame // zc+ self.skip_tail = self.extra_frame_right // zc+ self.return_length = (self.block_frame + self.sola_buffer_frame + self.sola_search_frame) // zc+ self.fade_in = torch.sin(0.5 * np.pi * torch.linspace(0, 1, self.sola_buffer_frame, device=dev)) ** 2+ self.fade_out = 1 - self.fade_in+ self.to16k = tat.Resample(device_sr, 16000).to(dev)+ self.from_model = tat.Resample(model.sr, device_sr).to(dev) if model.sr != device_sr else None+ self.prompt = None+ self._solver = None+ self._prev_loud = False+ self.last_infer_ms = 0.0+ if cfg.reference:+ self.set_reference(cfg.reference)++ @property+ def latency(self) -> int:+ return self.extra_frame_right + self.sola_buffer_frame + self.sola_search_frame // 2++ def set_reference(self, path: str) -> None:+ import librosa+ import torchaudio+ torch, m = self.torch, self.m+ wav, _ = librosa.load(path, sr=m.sr)+ wav = torch.from_numpy(wav[: int(m.sr * self.cfg.max_prompt_length)]).to(m.device)+ with torch.no_grad(), contextlib.redirect_stdout(io.StringIO()): # Seed-VC prints mel stats+ w16 = torchaudio.functional.resample(wav, m.sr, 16000)+ s_ori = m.semantic_fn(w16.unsqueeze(0))+ fb = torchaudio.compliance.kaldi.fbank(w16.unsqueeze(0), num_mel_bins=80, dither=0,+ sample_frequency=16000)+ style = m.campplus((fb - fb.mean(dim=0, keepdim=True)).unsqueeze(0))+ mel = m.to_mel(wav.unsqueeze(0))+ cond = m.model.length_regulator(s_ori, ylens=torch.LongTensor([mel.size(2)]).to(m.device),+ n_quantizers=3, f0=None)[0]+ self.prompt = (cond, mel, style)+ self.cfg.reference = path++ def _infer(self):+ torch, m, cfg = self.torch, self.m, self.cfg+ cond_p, mel_p, style = self.prompt+ s_alt = m.semantic_fn(self.input_wav_res.unsqueeze(0))+ ce_dit_frames = int((cfg.extra_time_ce - cfg.extra_time) * 50) # content-encoder vs DiT context gap+ s_alt = s_alt[:, ce_dit_frames:]+ tlen = torch.LongTensor([int((self.skip_head + self.return_length + self.skip_tail - ce_dit_frames)+ / 50 * m.sr // m.hop)]).to(m.device)+ cond = m.model.length_regulator(s_alt, ylens=tlen, n_quantizers=3, f0=None)[0]+ cat = torch.cat([cond_p, cond], dim=1)+ x_lens = torch.LongTensor([cat.size(1)]).to(m.device)+ use_graph = cfg.cuda_graph and m.device.type == "cuda"+ with torch.autocast(device_type=m.device.type, dtype=torch.float16 if m.fp16 else torch.float32,+ enabled=m.device.type == "cuda"):+ if use_graph:+ key = (tuple(cat.shape), tuple(mel_p.shape), cfg.diffusion_steps, cfg.inference_cfg_rate)+ if self._solver is None or self._solver.key != key:+ self._solver = None # release the old graph's memory pool first+ self._solver = _GraphedSolver(m, cat, x_lens, mel_p, style, cfg.diffusion_steps,+ cfg.inference_cfg_rate)+ mel = self._solver(cat, mel_p, style)+ else:+ mel = m.model.cfm.inference(cat, x_lens, mel_p, style, None, n_timesteps=cfg.diffusion_steps,+ inference_cfg_rate=cfg.inference_cfg_rate)+ mel = mel[:, :, mel_p.size(-1):]+ wave = m.vocoder(mel).squeeze().float()+ out_len = self.return_length * m.sr // 50+ tail = self.skip_tail * m.sr // 50+ wave = wave[-out_len - tail: -tail]+ return self.from_model(wave) if self.from_model is not None else wave++ def process_block(self, block: np.ndarray) -> np.ndarray:+ torch, F = self.torch, self.F+ if self.prompt is None:+ raise RuntimeError("no reference voice set; call set_reference(path)")+ n = self.block_frame+ assert len(block) == n, (len(block), n)+ x = torch.from_numpy(np.ascontiguousarray(block, dtype=np.float32)).to(self.m.device)+ self.input_wav = torch.roll(self.input_wav, -n)+ self.input_wav[-n:] = x+ self.input_wav_res = torch.roll(self.input_wav_res, -self.block_frame_16k)+ seg = self.input_wav[-n - 2 * self.zc:]+ self.input_wav_res[-320 * (n // self.zc + 1):] = self.to16k(seg)[320:]++ rms_db = 20 * np.log10(float(np.sqrt(np.mean(block**2))) + 1e-9)+ loud = rms_db > self.cfg.silence_threshold_db+ t0 = time.perf_counter()+ if loud or self._prev_loud:+ with torch.no_grad():+ infer = self._infer()+ else: # silence: skip the GPU entirely+ infer = torch.zeros(self.return_length * self.zc, device=self.m.device)+ self._prev_loud = loud+ self.last_infer_ms = (time.perf_counter() - t0) * 1000++ # SOLA (from DDSP-SVC via Seed-VC): find best-aligned offset, then crossfade.+ conv_in = infer[None, None, : self.sola_buffer_frame + self.sola_search_frame]+ num = F.conv1d(conv_in, self.sola_buffer[None, None, :])+ den = torch.sqrt(F.conv1d(conv_in**2, torch.ones(1, 1, self.sola_buffer_frame, device=self.m.device)) + 1e-8)+ off = int(torch.argmax(num[0, 0] / den[0, 0]).item())+ infer = infer[off:].clone()+ infer[: self.sola_buffer_frame] = infer[: self.sola_buffer_frame] * self.fade_in + self.sola_buffer * self.fade_out+ self.sola_buffer[:] = infer[n: n + self.sola_buffer_frame]+ return infer[:n].cpu().numpy().astype(np.float64)+++class SeedVCProcessor:+ """Adapts the fixed-block streamer to arbitrary host block sizes.++ ``mode="inline"`` — inference runs inline (host should use+ ``preferred_blocksize``); lowest latency.+ ``mode="threaded"`` — a worker thread converts while the audio+ callback only moves samples; adds one block of+ latency but never blocks the callback.+ """++ def __init__(self, spec: dict, sr: int, mode: str = "inline", device: str | None = None):+ self.spec = spec+ self.name = spec.get("name", "AI voice")+ self.cfg = StreamConfig.from_spec(spec)+ if spec.get("backend") == "onnx": # torch-free: ONNX Runtime + numpy (standalone build)+ from .onnx_backend import NumpyStreamer, OnnxSeedVCModel+ self.model = OnnxSeedVCModel.get(spec.get("onnx_dir", f"models/onnx/{spec.get('model')}"),+ spec.get("providers"))+ self.streamer = NumpyStreamer(self.model, sr, self.cfg)+ else:+ self.model = SeedVCModel.get(spec.get("model", "whisper-small-bigvgan"), device=device,+ checkpoint=spec.get("checkpoint"), config=spec.get("config"))+ self.streamer = SeedVCStreamer(self.model, sr, self.cfg)+ self.mode = mode+ self.sr = sr+ # inline: the host must call us with whole blocks; threaded+ # decouples, so the host keeps small low-latency buffers.+ self.preferred_blocksize = self.streamer.block_frame if mode == "inline" else None+ self.headroom = float(spec.get("rtf_headroom", 0.9)) # inference time as a fraction of a block+ self._in = np.zeros(0)+ self._out = np.zeros(self._prefill())+ self._q_in: queue.Queue = queue.Queue()+ self._q_out: queue.Queue = queue.Queue()+ self._lock = threading.Lock()+ self._stop = threading.Event()+ if mode == "threaded":+ self._worker = threading.Thread(target=self._run, name="seedvc-worker", daemon=True)+ self._worker.start()++ def _prefill(self) -> int:+ """Output delay that guarantees a block is converted before it is due:+ one block to accumulate + the worst-case inference time."""+ n = self.streamer.block_frame+ return n if self.mode == "inline" else n + int(self.headroom * n)++ @property+ def latency(self) -> int:+ return self.streamer.latency + self._prefill()++ def set_reference(self, path: str) -> None:+ with self._lock:+ self.streamer.set_reference(path)++ def warmup(self) -> None:+ if self.streamer.prompt is None:+ return+ block = np.random.default_rng(0).standard_normal(self.streamer.block_frame) * 0.05+ with self._lock:+ for _ in range(2): # 1st call compiles kernels for these shapes; time the 2nd+ self.streamer.process_block(block)+ self.streamer._prev_loud = False+ if self.mode == "threaded": # size the prefill from measured speed (+35 % margin)+ n = self.streamer.block_frame+ measured = self.streamer.last_infer_ms / 1000 * self.sr / n+ self.headroom = float(np.clip(1.35 * measured, 0.3, 1.0))+ self._out = np.zeros(self._prefill())++ def _run(self):+ while not self._stop.is_set():+ try:+ blk = self._q_in.get(timeout=0.1)+ except queue.Empty:+ continue+ with self._lock:+ self._q_out.put(self.streamer.process_block(blk))++ def close(self):+ self._stop.set()++ def process(self, x: np.ndarray) -> np.ndarray:+ n = self.streamer.block_frame+ self._in = np.concatenate([self._in, x])+ while len(self._in) >= n:+ blk, self._in = self._in[:n], self._in[n:]+ if self.mode == "inline":+ with self._lock:+ self._out = np.concatenate([self._out, self.streamer.process_block(blk)])+ else:+ self._q_in.put(blk)+ while not self._q_out.empty():+ self._out = np.concatenate([self._out, self._q_out.get_nowait()])+ if len(self._out) < len(x): # worker fell behind: emit silence rather than glitching+ self._out = np.concatenate([np.zeros(len(x) - len(self._out)), self._out])+ y, self._out = self._out[: len(x)], self._out[len(x):]+ return ydiff --git a/voxshift/assets/voxshift.ico b/voxshift/assets/voxshift.iconew file mode 100644index 0000000..544c791Binary files /dev/null and b/voxshift/assets/voxshift.ico differdiff --git a/voxshift/assets/voxshift.png b/voxshift/assets/voxshift.pngnew file mode 100644index 0000000..14706d3Binary files /dev/null and b/voxshift/assets/voxshift.png differdiff --git a/voxshift/audio/__init__.py b/voxshift/audio/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/voxshift/audio/cable.py b/voxshift/audio/cable.pynew file mode 100644index 0000000..8d927cf--- /dev/null+++ b/voxshift/audio/cable.py@@ -0,0 +1,156 @@+"""Virtual microphone ("cable") discovery, self-test and VB-CABLE install.++Other apps can only pick VoxShift up as a microphone through a virtual audio+driver: audio rendered to its *playback* endpoint reappears on its *capture*+endpoint. VoxShift works with the common ones and prefers them in this order.+"""+from __future__ import annotations++import logging+import platform+import shutil+import subprocess+import tempfile+import time+import urllib.request+import zipfile+from dataclasses import dataclass+from pathlib import Path++import numpy as np+import sounddevice as sd++log = logging.getLogger(__name__)++# (label, playback endpoint VoxShift writes to, capture endpoint apps select, caveat)+KNOWN_CABLES = [+ ("VB-CABLE", "CABLE Input", "CABLE Output", ""),+ ("VB-CABLE A", "CABLE-A Input", "CABLE-A Output", ""),+ ("VB-CABLE B", "CABLE-B Input", "CABLE-B Output", ""),+ ("VoiceMeeter", "VoiceMeeter Input", "VoiceMeeter Output", ""),+ ("VoiceMeeter AUX", "VoiceMeeter AUX Input", "VoiceMeeter AUX Output", ""),+ ("Virtual Audio Cable", "Line 1 (Virtual Audio Cable)", "Line 1 (Virtual Audio Cable)", ""),+]++VBCABLE_URL = "https://download.vb-audio.com/Download_CABLE/VBCABLE_Driver_Pack45.zip"+VBCABLE_SIGNERS = ("BUREL VINCENT", "Vincent Burel", "VB-Audio") # VB-Audio's code-signing subject+++@dataclass+class Cable:+ label: str+ playback: str # full device name VoxShift outputs to+ capture: str # full device name to choose as the mic in Discord/OBS/games+ caveat: str = ""+++def find_cables(hostapi: str | None = None, devices=None) -> list[Cable]:+ """Return every known virtual cable whose playback AND capture ends are present."""+ if devices is None:+ from .engine import default_hostapi, list_devices+ devices = list_devices(None, hostapi or default_hostapi())+ outs = [d["name"] for d in devices if d["max_output_channels"] > 0]+ ins = [d["name"] for d in devices if d["max_input_channels"] > 0]+ found = []+ for label, play, cap, caveat in KNOWN_CABLES:+ p = next((n for n in outs if n.lower().startswith(play.lower())), None)+ c = next((n for n in ins if n.lower().startswith(cap.lower())), None)+ if p and c:+ found.append(Cable(label, p, c, caveat))+ return found+++def self_test(cable: Cable, hostapi: str | None = None, seconds: float = 1.0) -> tuple[bool, float]:+ """Play a quiet tone into the cable and listen on its capture side.++ Returns (ok, tone-to-noise ratio in dB). Uses explicit streams because+ sounddevice's play()/rec() helpers share one global stream.+ """+ from .engine import default_hostapi, resolve_device+ api = hostapi or default_hostapi()+ o, i = resolve_device(cable.playback, "output", api), resolve_device(cable.capture, "input", api)+ sr, f = 48000, 997.0+ tone = (0.05 * np.sin(2 * np.pi * f * np.arange(int(sr * seconds)) / sr)).astype(np.float32)+ ext = sd.WasapiSettings(auto_convert=True) if api == "Windows WASAPI" else None+ chunks, pos = [], [0]++ def play_cb(out, frames, t, status):+ seg = tone[pos[0]:pos[0] + frames]+ out[:] = 0+ out[: len(seg)] = seg[:, None]+ pos[0] += frames++ with sd.InputStream(device=i, samplerate=sr, channels=1, dtype="float32", extra_settings=ext,+ callback=lambda d, f_, t, s: chunks.append(d[:, 0].copy())):+ time.sleep(0.15)+ with sd.OutputStream(device=o, samplerate=sr, channels=2, dtype="float32", extra_settings=ext,+ callback=play_cb):+ time.sleep(seconds + 0.2)+ x = np.concatenate(chunks) if chunks else np.zeros(1)+ spec = np.abs(np.fft.rfft(x * np.hanning(len(x))))+ k = int(round(f * len(x) / sr))+ ratio_db = float(20 * np.log10(spec[max(k - 2, 0): k + 3].max() / (np.median(spec) + 1e-12) + 1e-12))+ return ratio_db > 40, ratio_db+++def _env(exe: Path) -> dict:+ import os+ return {**os.environ, "VOXSHIFT_EXE": str(exe)} # avoids quoting paths into PowerShell+++def _verify_signature(exe: Path) -> str:+ """Require a valid Authenticode signature from VB-Audio before running anything."""+ ps = ("$s = Get-AuthenticodeSignature -LiteralPath $env:VOXSHIFT_EXE; "+ "'{0}|{1}' -f $s.Status, $s.SignerCertificate.Subject")+ out = subprocess.run(["powershell", "-NoProfile", "-Command", ps], env=_env(exe), capture_output=True,+ text=True, check=True, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)).stdout.strip()+ status, _, subject = out.partition("|")+ if status != "Valid" or not any(s.lower() in subject.lower() for s in VBCABLE_SIGNERS):+ raise RuntimeError(f"refusing to run {exe.name}: signature {status!r}, signer {subject!r}")+ return subject+++def download_vbcable(dest: Path | None = None) -> Path:+ """Download and unpack the official VB-CABLE pack and verify its setup's+ signature. Returns the verified setup executable (which needs the rest of+ the pack beside it)."""+ if platform.system() != "Windows":+ raise RuntimeError("VB-CABLE's installer is Windows-only (macOS: use BlackHole)")+ work = Path(tempfile.mkdtemp(prefix="vbcable-"))+ archive = work / "VBCABLE_Driver_Pack45.zip"+ print(f"downloading {VBCABLE_URL}")+ urllib.request.urlretrieve(VBCABLE_URL, archive)+ dest = Path(dest) if dest else work / "pack"+ if dest.exists():+ shutil.rmtree(dest)+ with zipfile.ZipFile(archive) as z:+ for member in z.namelist(): # reject path traversal+ if Path(member).is_absolute() or ".." in Path(member).parts:+ raise RuntimeError(f"unsafe path in archive: {member}")+ z.extractall(dest)+ # the x64 setup also installs the pack's ARM64 driver on ARM64 Windows+ exe = dest / ("VBCABLE_Setup_x64.exe" if platform.machine().endswith("64") else "VBCABLE_Setup.exe")+ if not exe.is_file():+ raise RuntimeError(f"setup not found in pack: {sorted(p.name for p in dest.iterdir())}")+ signer = _verify_signature(exe)+ print(f"verified signature: {signer}")+ log.info("VB-CABLE pack %s verified, signer %s", exe, signer)+ return exe+++def install_vbcable(silent: bool = False, hwnd: int | None = None) -> Path:+ """Download + verify VB-CABLE, then run its setup as administrator.++ Windows shows a UAC prompt (in front of ``hwnd`` when given). ``silent``+ passes the setup's documented ``-i -h`` switches (install, hidden UI);+ Windows still shows its own driver-consent dialog, which cannot be+ skipped. Otherwise click "Install Driver" in the VB-CABLE window. A+ reboot may be needed before the devices appear."""+ from ..winsys import run_elevated+ exe = download_vbcable()+ print("launching installer (approve the Windows prompts" + ("" if silent else ", click 'Install Driver'") + ")…")+ code = run_elevated(str(exe), "-i -h" if silent else "", hwnd)+ log.info("VB-CABLE setup exit code %s", code)+ if code != 0:+ raise RuntimeError(f"VB-CABLE setup returned exit code {code}")+ return exediff --git a/voxshift/audio/engine.py b/voxshift/audio/engine.pynew file mode 100644index 0000000..fecc84c--- /dev/null+++ b/voxshift/audio/engine.py@@ -0,0 +1,251 @@+"""Real-time audio engine (PortAudio via sounddevice).++Topology::++ mic ──► input gain ──► voice processor ──► + soundboard ──► limiter ──► virtual cable / output+ └──────────────► monitor ("hear myself")+"""+from __future__ import annotations++import collections+import sys+import threading+from dataclasses import dataclass++import numpy as np+import sounddevice as sd++from ..dsp.nodes import SoftLimiter, db_to_lin++PREFERRED_HOSTAPIS = ("Windows WASAPI", "Core Audio", "ALSA", "MME")+++def hostapi_name(index: int) -> str:+ return sd.query_hostapis(index)["name"]+++def list_devices(kind: str | None = None, hostapi: str | None = None) -> list[dict]:+ out = []+ for d in sd.query_devices():+ d = dict(d)+ d["hostapi_name"] = hostapi_name(d["hostapi"])+ if hostapi and d["hostapi_name"] != hostapi:+ continue+ if kind == "input" and d["max_input_channels"] < 1:+ continue+ if kind == "output" and d["max_output_channels"] < 1:+ continue+ out.append(d)+ return out+++def default_hostapi() -> str:+ names = [h["name"] for h in sd.query_hostapis()]+ for n in PREFERRED_HOSTAPIS:+ if n in names:+ return n+ return names[0]+++class NoVirtualCable(RuntimeError):+ pass+++_CLI = "voxshift-cli" if getattr(sys, "frozen", False) else "python -m voxshift"+NO_CABLE_HELP = (+ "No virtual microphone found, so other apps cannot hear VoxShift.\n"+ f" * install VB-CABLE: {_CLI} cable --install (or 'Set up virtual microphone' in the app)\n"+ " * or pass --output <device> to send the voice somewhere else")+++def resolve_device(spec: str | int | None, kind: str, hostapi: str | None = None) -> int | None:+ """Accept an index, an exact name, a case-insensitive substring, or+ ``"virtual"`` for the first detected virtual-cable playback endpoint."""+ if kind == "output" and isinstance(spec, str) and spec.lower() == "virtual":+ from .cable import find_cables+ cables = find_cables(hostapi)+ if not cables:+ raise NoVirtualCable(NO_CABLE_HELP)+ spec = cables[0].playback+ if spec is None or spec == "":+ if hostapi:+ h = next(h for h in sd.query_hostapis() if h["name"] == hostapi)+ idx = h[f"default_{kind}_device"]+ return idx if idx >= 0 else None+ return None+ if isinstance(spec, int) or str(spec).isdigit():+ return int(spec)+ cands = list_devices(kind, hostapi)+ for d in cands:+ if d["name"] == spec:+ return d["index"]+ for d in cands:+ if str(spec).lower() in d["name"].lower():+ return d["index"]+ raise ValueError(f"no {kind} device matching {spec!r}")+++@dataclass+class Meters:+ input_db: float = -120.0+ output_db: float = -120.0+ cpu_ms: float = 0.0+ xruns: int = 0+++def _db(x: np.ndarray) -> float:+ return 20 * np.log10(float(np.sqrt(np.mean(x**2))) + 1e-9) if len(x) else -120.0+++class _MonitorFifo:+ def __init__(self, max_samples: int):+ self.buf: collections.deque = collections.deque()+ self.size = 0+ self.max = max_samples+ self.lock = threading.Lock()++ def push(self, x: np.ndarray):+ with self.lock:+ self.buf.append(x)+ self.size += len(x)+ while self.size > self.max and self.buf: # drop oldest to bound latency+ self.size -= len(self.buf.popleft())++ def pull(self, n: int) -> np.ndarray:+ out = np.zeros(n, dtype=np.float32)+ pos = 0+ with self.lock:+ while pos < n and self.buf:+ chunk = self.buf[0]+ take = min(n - pos, len(chunk))+ out[pos:pos + take] = chunk[:take]+ pos += take+ if take == len(chunk):+ self.buf.popleft()+ else:+ self.buf[0] = chunk[take:]+ self.size -= take+ return out+++class AudioEngine:+ def __init__(self, input_device=None, output_device=None, monitor_device=None,+ samplerate: int = 48000, blocksize: int = 512, hostapi: str | None = None):+ self.hostapi = hostapi or default_hostapi()+ self.input_device = resolve_device(input_device, "input", self.hostapi)+ self.output_device = resolve_device(output_device, "output", self.hostapi)+ self.monitor_device = resolve_device(monitor_device, "output", self.hostapi) if monitor_device else None+ self.sr = samplerate+ self.default_blocksize = blocksize+ self.processor = None+ self.voice_enabled = True+ self.mic_muted = False+ self.hear_myself = self.monitor_device is not None+ self.input_gain_db = 0.0+ self.output_gain_db = 0.0+ self.monitor_gain_db = -6.0+ self.meters = Meters()+ self._limiter = SoftLimiter(samplerate, ceiling_db=-0.5)+ self._sounds: list[np.ndarray] = []+ self._lock = threading.Lock()+ self._stream = None+ self._monitor_stream = None+ self._monitor = _MonitorFifo(samplerate // 5)+ self._blocksize = blocksize++ # ------------------------------------------------------------------ control+ def set_processor(self, processor) -> None:+ old = self.processor+ with self._lock:+ self.processor = processor+ if old is not None and hasattr(old, "close"):+ old.close()+ want = getattr(processor, "preferred_blocksize", None) or self.default_blocksize+ if self._stream is not None and want != self._blocksize:+ self.stop()+ self.start()++ def play_sound(self, data: np.ndarray, sr: int, gain_db: float = 0.0) -> None:+ """Soundboard: mix a clip into the output (and monitor)."""+ from scipy.signal import resample_poly+ if data.ndim > 1:+ data = data.mean(axis=1)+ if sr != self.sr:+ g = np.gcd(sr, self.sr)+ data = resample_poly(data, self.sr // g, sr // g)+ with self._lock:+ self._sounds.append(data.astype(np.float64) * db_to_lin(gain_db))++ def stop_sounds(self) -> None:+ with self._lock:+ self._sounds.clear()++ # ------------------------------------------------------------------ streams+ def _extra(self):+ if self.hostapi == "Windows WASAPI":+ return sd.WasapiSettings(auto_convert=True)+ return None++ def start(self) -> None:+ self._blocksize = getattr(self.processor, "preferred_blocksize", None) or self.default_blocksize+ out_ch = min(2, sd.query_devices(self.output_device or sd.default.device[1])["max_output_channels"])+ self._out_ch = out_ch+ extra = self._extra()+ self._stream = sd.Stream(device=(self.input_device, self.output_device), samplerate=self.sr,+ blocksize=self._blocksize, channels=(1, out_ch), dtype="float32",+ callback=self._callback, extra_settings=(extra, extra), latency="low")+ if self.monitor_device is not None:+ mch = min(2, sd.query_devices(self.monitor_device)["max_output_channels"])+ self._monitor_stream = sd.OutputStream(device=self.monitor_device, samplerate=self.sr,+ blocksize=0, channels=mch, dtype="float32",+ callback=self._monitor_cb, extra_settings=extra,+ latency="low")+ self._monitor_stream.start()+ self._stream.start()++ def stop(self) -> None:+ for s in (self._stream, self._monitor_stream):+ if s is not None:+ s.stop()+ s.close()+ self._stream = self._monitor_stream = None++ @property+ def running(self) -> bool:+ return self._stream is not None and self._stream.active++ @property+ def stream_latency_ms(self) -> float:+ if self._stream is None:+ return 0.0+ lat = self._stream.latency+ return 1000 * (sum(lat) if isinstance(lat, tuple) else lat)++ def _monitor_cb(self, outdata, frames, t, status):+ y = self._monitor.pull(frames) * db_to_lin(self.monitor_gain_db) if self.hear_myself else np.zeros(frames)+ outdata[:] = np.repeat(y[:, None], outdata.shape[1], axis=1)++ def _callback(self, indata, outdata, frames, t, status):+ import time+ t0 = time.perf_counter()+ if status:+ self.meters.xruns += 1+ x = indata[:, 0].astype(np.float64) * (0.0 if self.mic_muted else db_to_lin(self.input_gain_db))+ with self._lock:+ proc = self.processor+ y = proc.process(x) if (proc is not None and self.voice_enabled) else x+ if self._sounds:+ keep = []+ for s in self._sounds:+ n = min(frames, len(s))+ y[:n] += s[:n]+ if len(s) > frames:+ keep.append(s[frames:])+ self._sounds = keep+ y = self._limiter.process(y * db_to_lin(self.output_gain_db)).astype(np.float32)+ outdata[:] = np.repeat(y[:, None], outdata.shape[1], axis=1)+ if self.hear_myself and self._monitor_stream is not None:+ self._monitor.push(y)+ self.meters.input_db = _db(x)+ self.meters.output_db = _db(y)+ self.meters.cpu_ms = (time.perf_counter() - t0) * 1000diff --git a/voxshift/cli.py b/voxshift/cli.pynew file mode 100644index 0000000..ecc3e32--- /dev/null+++ b/voxshift/cli.py@@ -0,0 +1,220 @@+"""Command-line interface: ``python -m voxshift <command>``."""+from __future__ import annotations++import argparse+import sys+import time++import numpy as np+++def _ai_overrides(a) -> dict:+ return {"diffusion_steps": a.diffusion_steps, "block_time": a.block_time,+ "inference_cfg_rate": a.cfg_rate}+++def cmd_devices(a):+ from .audio.engine import default_hostapi, list_devices+ api = a.hostapi or default_hostapi()+ print(f"host API: {api}")+ for kind in ("input", "output"):+ print(f"\n{kind} devices:")+ for d in list_devices(kind, api):+ print(f" [{d['index']:>3}] {d['name']} ({int(d['default_samplerate'])} Hz)")+++def cmd_voices(a):+ from .presets import list_presets+ for key, spec in list_presets().items():+ tag = "AI " if spec.get("engine") else "DSP"+ print(f" {key:<18} {tag} {spec.get('name', key)} — {spec.get('description', '')}")+++def cmd_convert(a):+ import soundfile as sf+ from scipy.signal import resample_poly++ from .presets import build_processor, load_spec++ data, sr_in = sf.read(a.input, always_2d=True)+ x = data.mean(axis=1)+ sr = a.sr+ if sr_in != sr:+ g = np.gcd(sr_in, sr)+ x = resample_poly(x, sr // g, sr_in // g)+ spec = load_spec(a.voice)+ t0 = time.perf_counter()+ proc = build_processor(spec, sr, reference=a.reference, device=a.device, **_ai_overrides(a))+ load_s = time.perf_counter() - t0+ block = getattr(proc, "preferred_blocksize", None) or a.blocksize+ lat = proc.latency+ padded = np.concatenate([x, np.zeros(lat + block)])+ out = []+ t0 = time.perf_counter()+ for i in range(0, len(padded), block):+ chunk = padded[i:i + block]+ if len(chunk) < block:+ chunk = np.concatenate([chunk, np.zeros(block - len(chunk))])+ out.append(proc.process(chunk))+ proc_s = time.perf_counter() - t0+ y = np.concatenate(out)[lat: lat + len(x)]+ peak = np.max(np.abs(y)) if len(y) else 0+ if peak > 0.99:+ y = y * (0.99 / peak)+ sf.write(a.output, y.astype(np.float32), sr)+ dur = len(x) / sr+ print(f"{spec.get('name')}: {dur:.2f}s audio processed in {proc_s:.2f}s "+ f"(RTF {proc_s / max(dur, 1e-9):.3f}, latency {1000 * lat / sr:.1f} ms"+ + (f", model load {load_s:.1f}s" if load_s > 0.5 else "") + f") -> {a.output}")+++def cmd_cable(a):+ from .audio.cable import download_vbcable, find_cables, install_vbcable, self_test+ from .audio.engine import default_hostapi+ if a.download: # used by the installer: it runs the verified setup elevated itself+ print(download_vbcable(a.download))+ return+ if a.install:+ install_vbcable(silent=a.silent)+ print("\nVB-CABLE installed. Reboot if the installer asked you to, then run `python -m voxshift cable`.")+ return+ api = a.hostapi or default_hostapi()+ cables = find_cables(api)+ if not cables:+ from .audio.engine import NO_CABLE_HELP+ raise SystemExit(NO_CABLE_HELP)+ for c in cables:+ ok, ratio = self_test(c, api) if not a.no_test else (None, 0.0)+ verdict = "untested" if ok is None else ("working" if ok else f"NOT passing audio ({ratio:.0f} dB)")+ print(f"{c.label}: VoxShift -> '{c.playback}' -> apps pick mic '{c.capture}' [{verdict}]")+ if c.caveat:+ print(f" note: {c.caveat}")+++def cmd_live(a):+ import sounddevice as sd++ from .audio.cable import find_cables+ from .audio.engine import AudioEngine, NoVirtualCable+ from .presets import build_processor, load_spec++ try:+ eng = AudioEngine(a.input, a.output, a.monitor, samplerate=a.sr, blocksize=a.blocksize, hostapi=a.hostapi)+ except NoVirtualCable as e:+ raise SystemExit(str(e))+ spec = load_spec(a.voice)+ proc = build_processor(spec, a.sr, reference=a.reference, ai_mode=a.ai_mode, device=a.device,+ **_ai_overrides(a))+ if hasattr(proc, "warmup"):+ print("warming up model…")+ proc.warmup()+ eng.set_processor(proc)+ eng.start()+ print(f"live: {spec.get('name')} | in={eng.input_device} out={eng.output_device} "+ f"monitor={eng.monitor_device} | Ctrl+C to stop")+ out_name = sd.query_devices(eng.output_device)["name"]+ cable = next((c for c in find_cables(eng.hostapi) if c.playback == out_name), None)+ if cable:+ print(f"-> in Discord/OBS/games choose the microphone '{cable.capture}'")+ if cable.caveat:+ print(f" note: {cable.caveat}")+ try:+ while True:+ m = eng.meters+ extra = f" ai={proc.streamer.last_infer_ms:5.0f}ms" if hasattr(proc, "streamer") else ""+ sys.stdout.write(f"\r in {m.input_db:6.1f} dB out {m.output_db:6.1f} dB "+ f"dsp {m.cpu_ms:5.1f} ms{extra} xruns {m.xruns} ")+ sys.stdout.flush()+ time.sleep(0.2)+ except KeyboardInterrupt:+ pass+ finally:+ eng.stop()+ print()+++def cmd_gui(a):+ from .gui import main+ main(["--minimized"] if a.minimized else [])+++def cmd_export_onnx(a):+ from .ai.onnx_export import export+ export(a.model, a.out_dir, opset=a.opset, fp16=not a.fp32)+++def build_parser() -> argparse.ArgumentParser:+ p = argparse.ArgumentParser(prog="voxshift", description="Local real-time voice changer.")+ sub = p.add_subparsers(dest="cmd", required=True)++ s = sub.add_parser("devices", help="list audio devices")+ s.add_argument("--hostapi")+ s.set_defaults(fn=cmd_devices)++ sub.add_parser("voices", help="list voice presets").set_defaults(fn=cmd_voices)++ def common(s):+ s.add_argument("--voice", "-v", default="robot")+ s.add_argument("--reference", "-r", help="target-speaker WAV for AI voices")+ s.add_argument("--sr", type=int, default=48000)+ s.add_argument("--blocksize", type=int, default=512)+ s.add_argument("--device", help="torch device for AI voices (cuda / cpu)")+ s.add_argument("--diffusion-steps", type=int)+ s.add_argument("--block-time", type=float)+ s.add_argument("--cfg-rate", type=float)++ s = sub.add_parser("convert", help="render a file through a voice")+ s.add_argument("input")+ s.add_argument("output")+ common(s)+ s.set_defaults(fn=cmd_convert)++ s = sub.add_parser("live", help="run the real-time voice changer")+ common(s)+ s.add_argument("--input", "-i", help="microphone (index or name substring)")+ s.add_argument("--output", "-o", default="virtual",+ help="'virtual' (default: first detected virtual cable) or a device name/index")+ s.add_argument("--monitor", "-m", help="headphones for 'hear myself'")+ s.add_argument("--hostapi")+ s.add_argument("--ai-mode", choices=["inline", "threaded"], default="inline")+ s.set_defaults(fn=cmd_live)++ s = sub.add_parser("cable", help="find and self-test virtual microphones, or install VB-CABLE")+ s.add_argument("--install", action="store_true", help="download, verify and launch the VB-CABLE installer")+ s.add_argument("--silent", action="store_true", help="with --install: hidden setup UI (-i -h)")+ s.add_argument("--download", metavar="DIR", help="only download + verify the VB-CABLE pack into DIR")+ s.add_argument("--no-test", action="store_true", help="skip the loopback tone test")+ s.add_argument("--hostapi")+ s.set_defaults(fn=cmd_cable)++ s = sub.add_parser("gui", help="open the desktop app")+ s.add_argument("--minimized", action="store_true", help="start in the system tray")+ s.set_defaults(fn=cmd_gui)++ s = sub.add_parser("export-onnx", help="export the AI networks to ONNX")+ s.add_argument("--model", default="whisper-small-bigvgan")+ s.add_argument("--out-dir", default="models/onnx")+ s.add_argument("--opset", type=int, default=17)+ s.add_argument("--fp32", action="store_true", help="keep every network in fp32")+ s.set_defaults(fn=cmd_export_onnx)+ return p+++def main(argv=None):+ a = build_parser().parse_args(argv)+ if getattr(sys, "frozen", False): # the installer runs us hidden: keep a record+ import logging++ from .paths import log_dir+ logging.basicConfig(filename=log_dir() / "voxshift-cli.log", level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s: %(message)s")+ try:+ a.fn(a)+ except Exception as e:+ import logging+ logging.getLogger("voxshift.cli").exception("command %s failed", a.cmd)+ raise SystemExit(f"error: {e}")+++if __name__ == "__main__":+ main()diff --git a/voxshift/dsp/__init__.py b/voxshift/dsp/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/voxshift/dsp/graph.py b/voxshift/dsp/graph.pynew file mode 100644index 0000000..8640faa--- /dev/null+++ b/voxshift/dsp/graph.py@@ -0,0 +1,191 @@+"""Voice graphs: JSON presets → node chains with modulated parameters.++A voice is a graph of effect nodes whose parameters can be driven by+generators (oscillators, random walks, sequences). The JSON schema::++ {+ "name": "Robot",+ "chain": [+ {"type": "Vocoder", "params": {"carrier_hz": 110}},+ {"type": "RingModulation",+ "params": {"freq": {"lfo": {"rate": 0.3, "min": 30, "max": 60}}}},+ {"type": "Parallel", "branches": [[...], [...]], "gains_db": [0, -6]}+ ]+ }++Modulated values (``lfo`` / ``random`` / ``sequence``) are re-evaluated once+per processed block.+"""+from __future__ import annotations++import json+import math+from dataclasses import dataclass, field+from pathlib import Path++import numpy as np++from .nodes import NODE_TYPES, LatencyDelay, Node, db_to_lin+++class Modulator:+ def value(self, t: float) -> float: # pragma: no cover - interface+ raise NotImplementedError+++class LFO(Modulator):+ """Periodic modulator (sine / triangle / square / saw)."""++ def __init__(self, rate=1.0, min=0.0, max=1.0, shape="sine", phase=0.0):+ self.rate, self.lo, self.hi, self.shape, self.phase = rate, min, max, shape, phase++ def value(self, t):+ ph = (t * self.rate + self.phase) % 1.0+ if self.shape == "sine":+ u = 0.5 * (1 - math.cos(2 * math.pi * ph))+ elif self.shape == "triangle":+ u = 1 - abs(2 * ph - 1)+ elif self.shape == "square":+ u = 1.0 if ph < 0.5 else 0.0+ else: # saw+ u = ph+ return self.lo + (self.hi - self.lo) * u+++class RandomWalk(Modulator):+ """Random target values with optional smoothing."""++ def __init__(self, min=0.0, max=1.0, interval_s=0.5, smooth=0.5, seed=0):+ self.lo, self.hi, self.interval, self.smooth = min, max, interval_s, smooth+ self.rng = np.random.default_rng(seed)+ self.cur = self.target = (min + max) / 2+ self.next_t = 0.0++ def value(self, t):+ if t >= self.next_t:+ self.target = float(self.rng.uniform(self.lo, self.hi))+ self.next_t = t + self.interval+ self.cur = self.smooth * self.cur + (1 - self.smooth) * self.target+ return self.cur+++class Sequence(Modulator):+ """Steps through a list of values."""++ def __init__(self, values, interval_s=0.25):+ self.values, self.interval = list(values), interval_s++ def value(self, t):+ return self.values[int(t / self.interval) % len(self.values)]+++MODULATORS = {"lfo": LFO, "random": RandomWalk, "sequence": Sequence}+++def _split_params(params: dict):+ static, mods = {}, {}+ for k, v in params.items():+ if isinstance(v, dict) and len(v) == 1 and next(iter(v)) in MODULATORS:+ kind, cfg = next(iter(v.items()))+ mods[k] = MODULATORS[kind](**cfg)+ else:+ static[k] = v+ return static, mods+++@dataclass+class _Slot:+ node: "Node | Parallel"+ mods: dict = field(default_factory=dict)+ bypass: bool = False+++class Parallel:+ """Runs branches side by side, aligns their latency and sums them."""++ def __init__(self, sr, branches, gains_db=None):+ self.chains = [Chain(sr, b) for b in branches]+ self.gains = [db_to_lin(g) for g in (gains_db or [0.0] * len(branches))]+ lat = max(c.latency for c in self.chains)+ for c in self.chains:+ if c.latency < lat:+ c.slots.append(_Slot(LatencyDelay(sr, samples=lat - c.latency)))+ self.latency = lat++ def process(self, x, t):+ return sum(g * c.process(x, t) for g, c in zip(self.gains, self.chains))+++class Chain:+ def __init__(self, sr: int, spec: list[dict]):+ self.sr = sr+ self.slots: list[_Slot] = []+ for item in spec:+ kind = item["type"]+ if kind == "Parallel":+ self.slots.append(_Slot(Parallel(sr, item["branches"], item.get("gains_db"))))+ continue+ if kind not in NODE_TYPES:+ raise ValueError(f"unknown node type {kind!r}; known: {sorted(NODE_TYPES)}")+ static, mods = _split_params(item.get("params", {}))+ node = NODE_TYPES[kind](sr, **static)+ if mods: # initialise modulated params at t=0+ node.set(**{k: m.value(0.0) for k, m in mods.items()})+ self.slots.append(_Slot(node, mods, item.get("bypass", False)))++ @property+ def latency(self) -> int:+ return sum(s.node.latency for s in self.slots if not s.bypass)++ def process(self, x: np.ndarray, t: float) -> np.ndarray:+ for s in self.slots:+ if s.bypass:+ continue+ if isinstance(s.node, Parallel):+ x = s.node.process(x, t)+ continue+ if s.mods:+ s.node.set(**{k: m.value(t) for k, m in s.mods.items()})+ x = s.node.process(x)+ return x+++class Voice:+ """A loaded voice preset, ready to process a mono stream."""++ def __init__(self, spec: dict, sr: int):+ self.spec = spec+ self.name = spec.get("name", "Unnamed")+ self.sr = sr+ self.chain = Chain(sr, spec.get("chain", []))+ self.t = 0.0++ @property+ def latency(self) -> int:+ return self.chain.latency++ def process(self, x: np.ndarray) -> np.ndarray:+ y = self.chain.process(np.asarray(x, dtype=np.float64), self.t)+ self.t += len(x) / self.sr+ return y+++VOICES_DIR = Path(__file__).resolve().parent.parent / "voices"+++def list_voices(extra_dirs: list[Path] | None = None) -> dict[str, Path]:+ found = {}+ for d in [VOICES_DIR, *(extra_dirs or [])]:+ for p in sorted(Path(d).glob("*.json")):+ found[p.stem] = p+ return found+++def load_voice(name_or_path: str, sr: int, extra_dirs: list[Path] | None = None) -> Voice:+ p = Path(name_or_path)+ if not p.is_file():+ voices = list_voices(extra_dirs)+ if name_or_path not in voices:+ raise KeyError(f"voice {name_or_path!r} not found; available: {', '.join(voices)}")+ p = voices[name_or_path]+ return Voice(json.loads(p.read_text(encoding="utf-8")), sr)diff --git a/voxshift/dsp/nodes.py b/voxshift/dsp/nodes.pynew file mode 100644index 0000000..33076be--- /dev/null+++ b/voxshift/dsp/nodes.py@@ -0,0 +1,622 @@+"""DSP node library.++Every node processes mono float64 blocks of any length and keeps its own+state, so a voice is just an ordered graph of nodes driven block-by-block.+"""+from __future__ import annotations++import math++import numpy as np+from scipy.signal import lfilter++from .stft import StreamingSTFT, cepstral_envelope, wrap_phase++NODE_TYPES: dict[str, type["Node"]] = {}+++def register(name: str):+ def deco(cls):+ NODE_TYPES[name] = cls+ cls.type_name = name+ return cls+ return deco+++def db_to_lin(db: float) -> float:+ return 10.0 ** (db / 20.0)+++class Node:+ type_name = "Node"+ defaults: dict = {}++ def __init__(self, sr: int, **params):+ self.sr = sr+ self.params = dict(self.defaults)+ self.params.update(params)+ self.setup()++ def setup(self) -> None:+ pass++ def set(self, **params) -> None:+ changed = {k: v for k, v in params.items() if self.params.get(k) != v}+ if changed:+ self.params.update(changed)+ self.on_change(changed)++ def on_change(self, changed: dict) -> None:+ pass++ @property+ def latency(self) -> int:+ return 0++ def process(self, x: np.ndarray) -> np.ndarray:+ return x+++# --------------------------------------------------------------------------- basic++@register("Gain")+class Gain(Node):+ defaults = {"gain_db": 0.0}++ def process(self, x):+ return x * db_to_lin(self.params["gain_db"])+++@register("Biquad")+class Biquad(Node):+ """RBJ cookbook biquad filter."""+ defaults = {"kind": "lowpass", "freq": 1000.0, "q": 0.707, "gain_db": 0.0}++ def setup(self):+ self._design()+ self._zi = np.zeros(2)++ def on_change(self, changed):+ self._design()++ def _design(self):+ p = self.params+ f = min(max(float(p["freq"]), 10.0), self.sr * 0.49)+ w0 = 2 * math.pi * f / self.sr+ cw, sw = math.cos(w0), math.sin(w0)+ alpha = sw / (2 * float(p["q"]))+ A = 10 ** (float(p["gain_db"]) / 40)+ k = p["kind"]+ if k == "lowpass":+ b = [(1 - cw) / 2, 1 - cw, (1 - cw) / 2]; a = [1 + alpha, -2 * cw, 1 - alpha]+ elif k == "highpass":+ b = [(1 + cw) / 2, -(1 + cw), (1 + cw) / 2]; a = [1 + alpha, -2 * cw, 1 - alpha]+ elif k == "bandpass":+ b = [alpha, 0, -alpha]; a = [1 + alpha, -2 * cw, 1 - alpha]+ elif k == "notch":+ b = [1, -2 * cw, 1]; a = [1 + alpha, -2 * cw, 1 - alpha]+ elif k == "peaking":+ b = [1 + alpha * A, -2 * cw, 1 - alpha * A]; a = [1 + alpha / A, -2 * cw, 1 - alpha / A]+ elif k in ("lowshelf", "highshelf"):+ sq = 2 * math.sqrt(A) * alpha+ s = 1 if k == "lowshelf" else -1+ b = [A * ((A + 1) - s * (A - 1) * cw + sq),+ s * 2 * A * ((A - 1) - s * (A + 1) * cw),+ A * ((A + 1) - s * (A - 1) * cw - sq)]+ a = [(A + 1) + s * (A - 1) * cw + sq,+ -s * 2 * ((A - 1) + s * (A + 1) * cw),+ (A + 1) + s * (A - 1) * cw - sq]+ else:+ raise ValueError(f"unknown biquad kind {k!r}")+ self.b = np.array(b) / a[0]+ self.a = np.array(a) / a[0]++ def process(self, x):+ y, self._zi = lfilter(self.b, self.a, x, zi=self._zi)+ return y+++@register("ParametricEQ")+class ParametricEQ(Node):+ """Cascade of biquads."""+ defaults = {"bands": []}++ def setup(self):+ self.filters = [Biquad(self.sr, **b) for b in self.params["bands"]]++ def on_change(self, changed):+ self.setup()++ def process(self, x):+ for f in self.filters:+ x = f.process(x)+ return x+++# --------------------------------------------------------------------------- time-domain FX++@register("Delay")+class Delay(Node):+ """Feedback echo."""+ defaults = {"time_ms": 250.0, "feedback": 0.35, "mix": 0.4, "max_ms": 2000.0}++ def setup(self):+ self.size = int(self.sr * self.params["max_ms"] / 1000) + 1+ self.ring = np.zeros(self.size)+ self.w = 0++ def process(self, x):+ d = int(np.clip(self.params["time_ms"] * self.sr / 1000, 1, self.size - 1))+ fb, mix = float(self.params["feedback"]), float(self.params["mix"])+ out = np.empty_like(x)+ pos = 0+ while pos < len(x):+ n = min(d, len(x) - pos)+ idx_r = (self.w - d + np.arange(n)) % self.size+ idx_w = (self.w + np.arange(n)) % self.size+ delayed = self.ring[idx_r]+ chunk = x[pos:pos + n]+ out[pos:pos + n] = chunk + mix * delayed+ self.ring[idx_w] = chunk + fb * delayed+ self.w = (self.w + n) % self.size+ pos += n+ return out+++@register("ModDelay")+class ModDelay(Node):+ """LFO-modulated delay taps: chorus / flanger / vibrato."""+ defaults = {"base_ms": 15.0, "depth_ms": 4.0, "rate_hz": 0.8, "voices": 2, "mix": 0.5}++ def setup(self):+ self.hist = np.zeros(int(self.sr * 0.1) + 4)+ self.phase = 0.0++ def process(self, x):+ p = self.params+ n = len(x)+ H = len(self.hist)+ ext = np.concatenate([self.hist, x])+ t = self.phase + np.arange(n) * p["rate_hz"] / self.sr+ wet = np.zeros(n)+ voices = max(1, int(p["voices"]))+ for v in range(voices):+ lfo = np.sin(2 * np.pi * (t + v / voices))+ d = (p["base_ms"] + p["depth_ms"] * lfo) * self.sr / 1000+ d = np.clip(d, 1, H - 2)+ pos = H + np.arange(n) - d+ i0 = np.floor(pos).astype(int)+ fr = pos - i0+ wet += ext[i0] * (1 - fr) + ext[i0 + 1] * fr+ wet /= voices+ self.phase = (self.phase + n * p["rate_hz"] / self.sr) % 1.0+ self.hist = ext[-H:]+ mix = float(p["mix"])+ return x * (1 - mix) + wet * mix+++@register("Distortion")+class Distortion(Node):+ """Waveshaping distortion / overdrive."""+ defaults = {"drive_db": 12.0, "shape": "tanh", "mix": 1.0, "output_db": -6.0}++ def process(self, x):+ p = self.params+ g = db_to_lin(p["drive_db"])+ s = p["shape"]+ if s == "tanh":+ y = np.tanh(g * x)+ elif s == "hard":+ y = np.clip(g * x, -1, 1)+ elif s == "fold":+ y = np.sin(g * x * math.pi / 2)+ elif s == "fuzz":+ y = np.sign(x) * (1 - np.exp(-np.abs(g * x)))+ else:+ raise ValueError(s)+ y *= db_to_lin(p["output_db"])+ return x * (1 - p["mix"]) + y * p["mix"]+++@register("Bitcrusher")+class Bitcrusher(Node):+ defaults = {"bits": 8, "downsample": 4}++ def setup(self):+ self.hold = 0.0+ self.count = 0++ def process(self, x):+ ds = max(1, int(self.params["downsample"]))+ levels = 2 ** (int(self.params["bits"]) - 1)+ n = len(x)+ latch = (self.count + np.arange(n)) % ds == 0+ # sample-and-hold: each output holds the most recent latched input+ idx = np.maximum.accumulate(np.where(latch, np.arange(n), -1))+ held = np.where(idx >= 0, x[np.maximum(idx, 0)], self.hold)+ if latch.any():+ self.hold = x[idx[-1]]+ self.count += n+ return np.round(held * levels) / levels+++@register("RingModulation")+class RingModulation(Node):+ """Carrier multiplication — daleks, robots."""+ defaults = {"freq": 50.0, "mix": 1.0, "waveform": "sine"}++ def setup(self):+ self.phase = 0.0++ def process(self, x):+ n = len(x)+ ph = self.phase + np.arange(n) * self.params["freq"] / self.sr+ self.phase = (self.phase + n * self.params["freq"] / self.sr) % 1.0+ w = self.params["waveform"]+ car = np.sin(2 * np.pi * ph) if w == "sine" else np.sign(np.sin(2 * np.pi * ph))+ m = self.params["mix"]+ return x * (1 - m) + x * car * m+++@register("Tremolo")+class Tremolo(Node):+ defaults = {"rate_hz": 6.0, "depth": 0.5}++ def setup(self):+ self.phase = 0.0++ def process(self, x):+ n = len(x)+ ph = self.phase + np.arange(n) * self.params["rate_hz"] / self.sr+ self.phase = (self.phase + n * self.params["rate_hz"] / self.sr) % 1.0+ d = self.params["depth"]+ return x * (1 - d * 0.5 * (1 + np.sin(2 * np.pi * ph)))+++@register("Oscillator")+class Oscillator(Node):+ """Adds a generated signal — hum, static, beeps."""+ defaults = {"waveform": "noise", "freq": 60.0, "level_db": -40.0, "follow_input": False}++ def setup(self):+ self.phase = 0.0+ self.rng = np.random.default_rng(1234)++ def process(self, x):+ n = len(x)+ w = self.params["waveform"]+ if w == "noise":+ s = self.rng.standard_normal(n) * 0.3+ else:+ ph = self.phase + np.arange(n) * self.params["freq"] / self.sr+ self.phase = (self.phase + n * self.params["freq"] / self.sr) % 1.0+ s = np.sin(2 * np.pi * ph) if w == "sine" else 2 * (ph % 1.0) - 1+ s *= db_to_lin(self.params["level_db"])+ if self.params["follow_input"]:+ s *= min(1.0, float(np.sqrt(np.mean(x**2)) * 10))+ return x + s+++class _Envelope:+ """Sub-block RMS envelope follower shared by gate/compressor."""++ def __init__(self, sr, sub=32):+ self.sr, self.sub, self.env, self.gain = sr, sub, 0.0, 1.0++ def gains(self, x, target_fn, attack_ms, release_ms):+ n = len(x)+ nb = max(1, n // self.sub)+ a = math.exp(-self.sub / (self.sr * max(attack_ms, 0.1) / 1000))+ r = math.exp(-self.sub / (self.sr * max(release_ms, 0.1) / 1000))+ pts = np.empty(nb)+ for i, seg in enumerate(np.array_split(x, nb)):+ lvl = float(np.sqrt(np.mean(seg**2)) + 1e-12)+ tgt = target_fn(20 * math.log10(lvl))+ coef = a if tgt < self.gain else r+ self.gain = coef * self.gain + (1 - coef) * tgt+ pts[i] = self.gain+ return np.interp(np.arange(n), np.linspace(0, n - 1, nb), pts)+++@register("NoiseGate")+class NoiseGate(Node):+ """Downward noise gate."""+ defaults = {"threshold_db": -50.0, "attack_ms": 2.0, "release_ms": 120.0, "floor_db": -80.0}++ def setup(self):+ self.envf = _Envelope(self.sr)++ def process(self, x):+ p = self.params+ floor = db_to_lin(p["floor_db"])+ g = self.envf.gains(x, lambda lv: 1.0 if lv > p["threshold_db"] else floor,+ p["release_ms"], p["attack_ms"]) # open fast, close slow+ return x * g+++@register("Compressor")+class Compressor(Node):+ """Feed-forward compressor."""+ defaults = {"threshold_db": -20.0, "ratio": 4.0, "attack_ms": 5.0, "release_ms": 80.0, "makeup_db": 6.0}++ def setup(self):+ self.envf = _Envelope(self.sr)++ def process(self, x):+ p = self.params++ def target(lv):+ over = lv - p["threshold_db"]+ return db_to_lin(-over * (1 - 1 / p["ratio"])) if over > 0 else 1.0++ return x * self.envf.gains(x, target, p["attack_ms"], p["release_ms"]) * db_to_lin(p["makeup_db"])+++@register("PitchShift")+class PitchShift(Node):+ """Low-latency granular delay-line pitch shifter (~window/2 latency)."""+ defaults = {"semitones": 0.0, "window_ms": 40.0, "mix": 1.0}++ def setup(self):+ self.W = int(self.sr * self.params["window_ms"] / 1000)+ self.hist = np.zeros(self.W + 4)+ self.phase = 0.0++ def on_change(self, changed):+ if "window_ms" in changed:+ self.setup()++ @property+ def latency(self):+ return self.W // 2++ def process(self, x):+ r = 2 ** (self.params["semitones"] / 12)+ n, W, H = len(x), self.W, len(self.hist)+ ext = np.concatenate([self.hist, x])+ t = self.phase + np.arange(n) * (1 - r) / W+ out = np.zeros(n)+ for off in (0.0, 0.5):+ f = (t + off) % 1.0+ pos = H + np.arange(n) - 1 - f * W+ i0 = np.floor(pos).astype(int)+ fr = pos - i0+ out += (ext[i0] * (1 - fr) + ext[i0 + 1] * fr) * np.sin(np.pi * f) ** 2+ self.phase = (self.phase + n * (1 - r) / W) % 1.0+ self.hist = ext[-H:]+ m = self.params["mix"]+ return x * (1 - m) + out * m+++# --------------------------------------------------------------------------- spectral FX++class _SpectralNode(Node):+ defaults = {"n_fft": 2048, "hop": 512}++ def setup(self):+ self.stft = StreamingSTFT(int(self.params["n_fft"]), int(self.params["hop"]))+ self.stft.process_frame = self.frame+ self.k = np.arange(self.stft.n_bins)++ @property+ def latency(self):+ return self.stft.latency++ def frame(self, spec):+ return spec++ def process(self, x):+ return self.stft.process(x)+++@register("FormantPitchShifter")+class FormantPitchShifter(_SpectralNode):+ """Phase-vocoder pitch shift with independent formant shift and optional+ autotune."""+ defaults = {+ **_SpectralNode.defaults,+ "semitones": 0.0,+ "formant_semitones": 0.0,+ "preserve_formants": True,+ "autotune": 0.0, # 0..1 strength of snapping to scale+ "scale": "chromatic", # chromatic | major | minor+ "key": 0, # 0 = C+ "autotune_speed": 0.6, # 0 = slow glide, 1 = instant (robotic)+ }+ SCALES = {"chromatic": list(range(12)), "major": [0, 2, 4, 5, 7, 9, 11], "minor": [0, 2, 3, 5, 7, 8, 10]}++ def setup(self):+ super().setup()+ N, hop = self.stft.n_fft, self.stft.hop+ self.expct = 2 * np.pi * hop / N+ self.last_phase = np.zeros(self.stft.n_bins)+ self.sum_phase = np.zeros(self.stft.n_bins)+ self.n_ceps = max(8, int(self.sr / 650 * N / 2048))+ self.tune_ratio = 1.0++ def _detect_f0(self, spec):+ ac = np.fft.irfft(np.abs(spec) ** 2)+ lo, hi = int(self.sr / 800), int(self.sr / 70)+ if ac[0] <= 1e-9:+ return None+ seg = ac[lo:hi]+ i = int(np.argmax(seg))+ if seg[i] / ac[0] < 0.35 or i == 0 or i == len(seg) - 1:+ return None+ a, b, c = seg[i - 1], seg[i], seg[i + 1]+ shift = 0.5 * (a - c) / (a - 2 * b + c + 1e-12)+ return self.sr / (lo + i + shift)++ def _autotune_ratio(self, spec):+ p = self.params+ f0 = self._detect_f0(spec)+ target = 1.0+ if f0:+ midi = 69 + 12 * math.log2(f0 / 440)+ degrees = self.SCALES.get(p["scale"], self.SCALES["chromatic"])+ cands = [12 * o + d + p["key"] for o in range(-1, 11) for d in degrees]+ nearest = min(cands, key=lambda m: abs(m - midi))+ target = 2 ** ((nearest - midi) / 12 * p["autotune"])+ sp = float(p["autotune_speed"])+ self.tune_ratio = self.tune_ratio * (1 - sp) + target * sp+ return self.tune_ratio++ def frame(self, spec):+ p = self.params+ ratio = 2 ** (p["semitones"] / 12)+ if p["autotune"] > 0:+ ratio *= self._autotune_ratio(spec)+ mag = np.abs(spec)+ phase = np.angle(spec)+ dev = wrap_phase(phase - self.last_phase - self.k * self.expct)+ self.last_phase = phase+ true_bin = self.k + dev / self.expct++ preserve = p["preserve_formants"] or p["formant_semitones"] != 0+ if preserve:+ env = cepstral_envelope(mag, self.n_ceps)+ fine = mag / np.maximum(env, 1e-9)+ else:+ fine = mag++ tgt = np.round(self.k * ratio).astype(int)+ ok = tgt < len(self.k)+ syn_mag = np.zeros_like(mag)+ np.add.at(syn_mag, tgt[ok], fine[ok])+ syn_bin = np.zeros_like(mag)+ syn_bin[tgt[ok]] = true_bin[ok] * ratio++ if preserve:+ f_ratio = 2 ** (p["formant_semitones"] / 12)+ if not p["preserve_formants"]:+ f_ratio *= ratio+ syn_mag *= np.interp(self.k / f_ratio, self.k, env, right=env[-1] * 1e-3)++ self.sum_phase = wrap_phase(self.sum_phase + syn_bin * self.expct)+ return syn_mag * np.exp(1j * self.sum_phase)+++@register("Vocoder")+class Vocoder(_SpectralNode):+ """Channel vocoder: speech envelope imposed on a synthetic carrier — classic robot."""+ defaults = {**_SpectralNode.defaults, "n_fft": 1024, "hop": 256,+ "carrier_hz": 100.0, "waveform": "saw", "bands": 24, "mix": 1.0}++ def setup(self):+ super().setup()+ self.cphase = 0.0+ self.win = self.stft.window++ def frame(self, spec):+ p = self.params+ N, hop = self.stft.n_fft, self.stft.hop+ f = p["carrier_hz"] / self.sr+ ph = (self.cphase + np.arange(N) * f) % 1.0+ self.cphase = (self.cphase + hop * f) % 1.0+ car = 2 * ph - 1 if p["waveform"] == "saw" else np.sign(np.sin(2 * np.pi * ph))+ cspec = np.fft.rfft(car * self.win)+ width = max(1, len(self.k) // int(p["bands"]))+ ker = np.ones(width) / width+ env_in = np.convolve(np.abs(spec), ker, mode="same")+ env_c = np.convolve(np.abs(cspec), ker, mode="same") + 1e-9+ out = cspec * env_in / env_c+ return spec * (1 - p["mix"]) + out * p["mix"]+++@register("Whisperize")+class Whisperize(_SpectralNode):+ """Randomised phase → breathy whisper."""+ defaults = {**_SpectralNode.defaults, "n_fft": 1024, "hop": 256}++ def setup(self):+ super().setup()+ self.rng = np.random.default_rng(7)++ def frame(self, spec):+ return np.abs(spec) * np.exp(2j * np.pi * self.rng.random(len(spec)))+++@register("ConvolutionReverb")+class ConvolutionReverb(Node):+ """Convolution reverb with a synthetic room impulse response.++ Uniformly-partitioned overlap-save convolution: cost per block is one+ FFT pair plus a multiply-accumulate over IR partitions, independent of+ the IR length. The partition delay is absorbed into the pre-delay so the+ dry path stays at zero latency."""+ defaults = {"decay_s": 1.2, "predelay_ms": 20.0, "damping": 0.5, "mix": 0.3, "seed": 3, "partition": 512}++ def setup(self):+ p = self.params+ P = self.P = int(p["partition"])+ rng = np.random.default_rng(int(p["seed"]))+ n = int(self.sr * p["decay_s"])+ t = np.arange(n) / self.sr+ ir = rng.standard_normal(n) * np.exp(-6.9 * t / max(p["decay_s"], 1e-3))+ if p["damping"] > 0: # progressive high-frequency damping+ ir = lfilter([1 - p["damping"] * 0.9], [1, -p["damping"] * 0.9], ir)+ pre = max(0, int(self.sr * p["predelay_ms"] / 1000) - P)+ ir = np.concatenate([np.zeros(pre), ir])+ ir /= np.sqrt(np.sum(ir**2))+ K = -(-len(ir) // P)+ parts = np.zeros((K, P))+ parts.flat[: len(ir)] = ir+ self.H = np.fft.rfft(parts, n=2 * P, axis=1)+ self.X = np.zeros_like(self.H)+ self.w = 0+ self.prev = np.zeros(P)+ self.fifo_in = np.zeros(0)+ self.fifo_out = np.zeros(P)++ def on_change(self, changed):+ if set(changed) - {"mix"}:+ self.setup()++ def _block(self, b):+ P, K = self.P, len(self.H)+ self.w = (self.w + 1) % K+ self.X[self.w] = np.fft.rfft(np.concatenate([self.prev, b]))+ self.prev = b+ order = (self.w - np.arange(K)) % K+ Y = np.einsum("kb,kb->b", self.X[order], self.H)+ return np.fft.irfft(Y, 2 * P)[P:]++ def process(self, x):+ self.fifo_in = np.concatenate([self.fifo_in, x])+ outs = []+ while len(self.fifo_in) >= self.P:+ outs.append(self._block(self.fifo_in[: self.P]))+ self.fifo_in = self.fifo_in[self.P:]+ self.fifo_out = np.concatenate([self.fifo_out, *outs])+ wet, self.fifo_out = self.fifo_out[: len(x)], self.fifo_out[len(x):]+ m = self.params["mix"]+ return x * (1 - m) + wet * m+++@register("SoftLimiter")+class SoftLimiter(Node):+ defaults = {"ceiling_db": -1.0}++ def process(self, x):+ c = db_to_lin(self.params["ceiling_db"])+ return c * np.tanh(x / c)+++@register("LatencyDelay")+class LatencyDelay(Node):+ """Pure integer delay used to align parallel branches."""+ defaults = {"samples": 0}++ def setup(self):+ self.buf = np.zeros(int(self.params["samples"]))++ @property+ def latency(self):+ return len(self.buf)++ def process(self, x):+ if not len(self.buf):+ return x+ ext = np.concatenate([self.buf, x])+ self.buf = ext[len(x):]+ return ext[: len(x)]diff --git a/voxshift/dsp/stft.py b/voxshift/dsp/stft.pynew file mode 100644index 0000000..7e190a7--- /dev/null+++ b/voxshift/dsp/stft.py@@ -0,0 +1,60 @@+"""Streaming STFT framework shared by the spectral nodes.++Used by the spectral nodes (pitch/formant shifting, vocoder, whisper,+autotune): audio arrives in arbitrary block sizes, is framed+with a fixed hop, transformed, edited per frame, and overlap-added back.+Output latency is exactly ``n_fft`` samples regardless of block size.+"""+from __future__ import annotations++import numpy as np+++class StreamingSTFT:+ def __init__(self, n_fft: int = 2048, hop: int = 512):+ if n_fft % hop:+ raise ValueError("n_fft must be a multiple of hop")+ self.n_fft = n_fft+ self.hop = hop+ self.n_bins = n_fft // 2 + 1+ self.window = np.hanning(n_fft + 1)[:-1]+ # Hann analysis * Hann synthesis overlap-adds to sum(w^2)/hop.+ self.ola_gain = hop / np.sum(self.window**2)+ self._buf = np.zeros(n_fft - hop)+ self._ola = np.zeros(n_fft)+ # One hop of pre-roll guarantees the output FIFO never underruns.+ self._fifo = np.zeros(hop)++ @property+ def latency(self) -> int:+ return self.n_fft++ def process_frame(self, spec: np.ndarray) -> np.ndarray:+ return spec++ def process(self, x: np.ndarray) -> np.ndarray:+ self._buf = np.concatenate([self._buf, x])+ outs = []+ while len(self._buf) >= self.n_fft:+ spec = np.fft.rfft(self._buf[: self.n_fft] * self.window)+ y = np.fft.irfft(self.process_frame(spec), self.n_fft)+ self._ola += y * self.window * self.ola_gain+ outs.append(self._ola[: self.hop].copy())+ self._ola = np.concatenate([self._ola[self.hop:], np.zeros(self.hop)])+ self._buf = self._buf[self.hop:]+ if outs:+ self._fifo = np.concatenate([self._fifo, *outs])+ out, self._fifo = self._fifo[: len(x)], self._fifo[len(x):]+ return out+++def cepstral_envelope(mag: np.ndarray, n_coeffs: int) -> np.ndarray:+ """Smooth spectral envelope via cepstral liftering (used for formants)."""+ log_mag = np.log(np.maximum(mag, 1e-9))+ cep = np.fft.irfft(log_mag)+ cep[n_coeffs: len(cep) - n_coeffs + 1] = 0.0+ return np.exp(np.fft.rfft(cep).real)+++def wrap_phase(p: np.ndarray) -> np.ndarray:+ return (p + np.pi) % (2.0 * np.pi) - np.pidiff --git a/voxshift/gui.py b/voxshift/gui.pynew file mode 100644index 0000000..6008890--- /dev/null+++ b/voxshift/gui.py@@ -0,0 +1,655 @@+"""VoxShift desktop app: Tk + Sun Valley theme, tray icon, global hotkeys.++Starts the audio engine with the saved devices, routes the processed voice+into a virtual microphone, keeps running in the tray, and is controlled with+global hotkeys.+"""+from __future__ import annotations++import logging+import logging.handlers+import queue+import sys+import tempfile+import threading+import tkinter as tk+from pathlib import Path+from tkinter import filedialog, messagebox, ttk++from . import __version__, winsys+from .audio.cable import find_cables, install_vbcable+from .audio.engine import AudioEngine, NoVirtualCable, default_hostapi, list_devices+from .paths import FROZEN, log_dir+from .presets import build_processor, create_ai_voice, delete_user_voice, is_ai, list_presets+from .settings import Settings++SR = 48000+ASSETS = Path(__file__).resolve().parent / "assets"+log = logging.getLogger("voxshift")+++# ---------------------------------------------------------------------- dialogs+class NewAIVoiceDialog(tk.Toplevel):+ """Voicelab-style dialog: name + a reference clip (file or 10 s recording)."""++ def __init__(self, app: "App"):+ super().__init__(app.root)+ self.app, self.reference = app, None+ self.title("New AI voice")+ self.resizable(False, False)+ self.transient(app.root)+ f = ttk.Frame(self, padding=16)+ f.pack(fill="both")+ ttk.Label(f, text="Name").grid(row=0, column=0, sticky="w")+ self.name = ttk.Entry(f, width=36)+ self.name.grid(row=0, column=1, columnspan=2, sticky="ew", pady=4)+ ttk.Label(f, text="Target voice").grid(row=1, column=0, sticky="w")+ ttk.Button(f, text="Choose file…", command=self.pick).grid(row=1, column=1, sticky="ew", pady=4)+ self.rec_btn = ttk.Button(f, text="Record 10 s", command=self.record)+ self.rec_btn.grid(row=1, column=2, sticky="ew", padx=(6, 0), pady=4)+ self.ref_label = ttk.Label(f, text="No recording yet", foreground="#999")+ self.ref_label.grid(row=2, column=1, columnspan=2, sticky="w")+ ttk.Label(f, wraplength=360, foreground="#999", justify="left",+ text="3–10 seconds of one person speaking clearly, without music or noise. "+ "Only use voices you have permission to use.").grid(row=3, column=0, columnspan=3, pady=10)+ ttk.Button(f, text="Create voice", style="Accent.TButton", command=self.create).grid(+ row=4, column=2, sticky="e")+ self.name.focus_set()++ def pick(self):+ p = filedialog.askopenfilename(parent=self, filetypes=[("Audio", "*.wav *.flac *.ogg *.mp3")])+ if p:+ self.reference = p+ self.ref_label.config(text=Path(p).name)+ if not self.name.get():+ self.name.insert(0, Path(p).stem.replace("_", " ").title())++ def record(self):+ import sounddevice as sd+ import soundfile as sf+ dev = self.app.engine.input_device if self.app.engine else None+ self.rec_btn.state(["disabled"])+ out = Path(tempfile.mkdtemp()) / "recording.wav"++ def run():+ try:+ data = sd.rec(int(10 * SR), samplerate=SR, channels=1, device=dev, dtype="float32", blocking=True)+ sf.write(out, data[:, 0], SR)+ self.app.call_soon(lambda: self._recorded(out))+ except Exception as e: # shown to the user+ msg = str(e)+ self.app.call_soon(lambda: self.ref_label.config(text=f"Recording failed: {msg}"))+ finally:+ self.app.call_soon(lambda: self.rec_btn.state(["!disabled"]))++ for i in range(10, 0, -1):+ self.after((10 - i) * 1000, lambda i=i: self.ref_label.config(text=f"Recording… speak now ({i}s)"))+ threading.Thread(target=run, daemon=True).start()++ def _recorded(self, path):+ self.reference = str(path)+ self.ref_label.config(text="Recorded 10 s")++ def create(self):+ name = self.name.get().strip()+ if not name or not self.reference:+ messagebox.showwarning("New AI voice", "Give the voice a name and a recording.", parent=self)+ return+ key = create_ai_voice(name, self.reference)+ self.destroy()+ self.app.refresh_voices(select=key)+++class SettingsDialog(tk.Toplevel):+ def __init__(self, app: "App"):+ super().__init__(app.root)+ self.app, s = app, app.s+ self.title("Settings")+ self.resizable(False, False)+ self.transient(app.root)+ nb = ttk.Notebook(self, padding=10)+ nb.pack(fill="both", expand=True)++ audio = ttk.Frame(nb, padding=12)+ nb.add(audio, text="Audio")+ api = app.hostapi+ ins = ["(system default)"] + [d["name"] for d in list_devices("input", api)]+ outs = [d["name"] for d in list_devices("output", api)]+ cables = find_cables(api)+ self.inp = self._combo(audio, 0, "Microphone", ins, s.input_device or "(system default)")+ out_values = ["virtual"] + outs+ self.out = self._combo(audio, 1, "Voice output", out_values, s.output_device or "virtual")+ ttk.Label(audio, foreground="#999", text="'virtual' = the virtual microphone other apps listen to"+ ).grid(row=2, column=1, sticky="w")+ self.mon = self._combo(audio, 3, "Hear-myself device", ["(system default)"] + outs,+ s.monitor_device or "(system default)")+ self.gains = {}+ for i, (key, label) in enumerate([("input_gain_db", "Mic gain (dB)"), ("output_gain_db", "Voice gain (dB)"),+ ("monitor_gain_db", "Hear-myself volume (dB)")]):+ ttk.Label(audio, text=label).grid(row=4 + i, column=0, sticky="w", pady=4)+ var = tk.DoubleVar(value=getattr(s, key))+ ttk.Scale(audio, from_=-30, to=20, variable=var).grid(row=4 + i, column=1, sticky="ew")+ self.gains[key] = var++ vmic = ttk.Frame(nb, padding=12)+ nb.add(vmic, text="Virtual microphone")+ text = ("\n".join(f"• {c.label}: apps select '{c.capture}'" for c in cables)+ or "No virtual microphone is installed, so other apps cannot hear VoxShift.")+ ttk.Label(vmic, text=text, wraplength=420, justify="left").pack(anchor="w")+ ttk.Button(vmic, text="Install VB-CABLE…", command=app.install_cable).pack(anchor="w", pady=10)+ ttk.Button(vmic, text="Test virtual microphone", command=app.test_cable).pack(anchor="w")++ general = ttk.Frame(nb, padding=12)+ nb.add(general, text="General")+ self.autostart = tk.BooleanVar(value=winsys.get_autostart())+ self.minimized = tk.BooleanVar(value=s.start_minimized)+ self.to_tray = tk.BooleanVar(value=s.close_to_tray)+ ttk.Checkbutton(general, text="Start with Windows", variable=self.autostart).pack(anchor="w", pady=2)+ ttk.Checkbutton(general, text="Start minimized to the tray", variable=self.minimized).pack(anchor="w", pady=2)+ ttk.Checkbutton(general, text="Closing the window keeps VoxShift running in the tray",+ variable=self.to_tray).pack(anchor="w", pady=2)+ ttk.Label(general, text="Global hotkeys", font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(12, 2))+ self.hotkeys = {}+ for name, spec in s.hotkeys.items():+ row = ttk.Frame(general)+ row.pack(fill="x", pady=1)+ ttk.Label(row, text=name.replace("_", " ").capitalize(), width=22).pack(side="left")+ e = ttk.Entry(row, width=18)+ e.insert(0, spec)+ e.pack(side="left")+ if name in app.hotkey_errors:+ ttk.Label(row, text=app.hotkey_errors[name], foreground="#e66").pack(side="left", padx=6)+ self.hotkeys[name] = e++ bar = ttk.Frame(self, padding=(10, 0, 10, 10))+ bar.pack(fill="x")+ ttk.Button(bar, text="Save", style="Accent.TButton", command=self.save).pack(side="right")+ ttk.Button(bar, text="Cancel", command=self.destroy).pack(side="right", padx=6)++ @staticmethod+ def _combo(parent, row, label, values, current):+ ttk.Label(parent, text=label).grid(row=row, column=0, sticky="w", pady=4)+ c = ttk.Combobox(parent, values=values, width=48, state="readonly")+ c.set(current if current in values else values[0])+ c.grid(row=row, column=1, sticky="ew", padx=(8, 0))+ return c++ def save(self):+ s = self.app.s+ default = "(system default)"+ s.input_device = "" if self.inp.get() == default else self.inp.get()+ s.output_device = self.out.get()+ s.monitor_device = "" if self.mon.get() == default else self.mon.get()+ for key, var in self.gains.items():+ setattr(s, key, round(var.get(), 1))+ s.start_minimized, s.close_to_tray = self.minimized.get(), self.to_tray.get()+ s.hotkeys = {k: e.get().strip().lower() for k, e in self.hotkeys.items()}+ s.save()+ winsys.set_autostart(self.autostart.get())+ self.destroy()+ self.app.restart_engine()+ self.app.register_hotkeys()+++# ---------------------------------------------------------------------- main window+class App:+ def __init__(self, root: tk.Tk, minimized: bool = False):+ self.root = root+ self.s = Settings.load()+ self.hostapi = default_hostapi()+ self.engine: AudioEngine | None = None+ self.presets: dict[str, dict] = {}+ self.current_key: str | None = None+ self.hotkeys = None+ self.hotkey_errors: dict[str, str] = {}+ self.tray = None+ self._load_token = 0+ self._ui_queue: queue.SimpleQueue = queue.SimpleQueue()+ root.title("VoxShift")+ root.geometry("1000x640")+ root.minsize(860, 560)+ try:+ root.iconbitmap(default=str(ASSETS / "voxshift.ico"))+ except tk.TclError:+ pass+ self._theme()+ self._build()+ self.refresh_voices(select=self.s.voice)+ self.restart_engine()+ self.register_hotkeys()+ self._start_tray()+ root.protocol("WM_DELETE_WINDOW", self.on_close)+ if minimized or self.s.start_minimized:+ root.withdraw() if self.tray else root.iconify()+ root.after(400, self._first_run)+ self._tick()++ # -------------------------------------------------------------- layout+ def _theme(self):+ try:+ import sv_ttk+ sv_ttk.set_theme("dark")+ except Exception: # theme is cosmetic+ pass++ def _build(self):+ r = self.root+ head = ttk.Frame(r, padding=(14, 10))+ head.pack(fill="x")+ ttk.Label(head, text="VoxShift", font=("Segoe UI Semibold", 18)).pack(side="left")+ self.voice_var = tk.BooleanVar(value=self.s.voice_enabled)+ self.hear_var = tk.BooleanVar(value=self.s.hear_myself)+ self.mute_var = tk.BooleanVar(value=self.s.mic_muted)+ for text, var in (("Voice changer", self.voice_var), ("Hear myself", self.hear_var),+ ("Mute mic", self.mute_var)):+ ttk.Checkbutton(head, text=text, variable=var, style="Switch.TCheckbutton",+ command=self.apply_toggles).pack(side="left", padx=(24, 0))+ ttk.Button(head, text="Settings", command=lambda: SettingsDialog(self)).pack(side="right")+ self.meter = tk.Canvas(head, width=160, height=26, highlightthickness=0, bg="#1c1c1c")+ self.meter.pack(side="right", padx=12)++ self.banner = ttk.Frame(r, padding=(14, 6))+ self.banner_text = ttk.Label(self.banner, text="", foreground="#f0b429")+ self.banner_text.pack(side="left")+ self.banner_btn = ttk.Button(self.banner, text="Set up virtual microphone", command=self.install_cable)+ self.banner_btn.pack(side="right")++ self.status = tk.StringVar(value="Starting…") # packed before the body so it always gets space+ ttk.Label(r, textvariable=self.status, padding=(14, 6), foreground="#aaa").pack(fill="x", side="bottom")+ body = ttk.Frame(r, padding=(14, 4))+ body.pack(fill="both", expand=True)+ left = ttk.Frame(body)+ left.pack(side="left", fill="y")+ self.search = tk.StringVar()+ self.search.trace_add("write", lambda *_: self._fill_tree())+ ttk.Label(left, text="Search voices", foreground="#999").pack(anchor="w")+ ttk.Entry(left, textvariable=self.search, width=32).pack(fill="x")+ ttk.Button(left, text="+ New AI voice", style="Accent.TButton",+ command=lambda: NewAIVoiceDialog(self)).pack(fill="x", side="bottom")+ self.tree = ttk.Treeview(left, show="tree", selectmode="browse", height=12)+ self.tree.column("#0", width=290)+ self.tree.pack(fill="both", expand=True, pady=6)+ self.tree.bind("<<TreeviewSelect>>", lambda e: self._on_select())++ right = ttk.Frame(body, padding=(18, 0, 0, 0))+ right.pack(side="left", fill="both", expand=True)+ self.v_name = ttk.Label(right, text="", font=("Segoe UI Semibold", 16))+ self.v_name.pack(anchor="w")+ self.v_desc = ttk.Label(right, text="", wraplength=560, justify="left", foreground="#aaa")+ self.v_desc.pack(anchor="w", pady=(2, 8))+ self.ai_box = ttk.Frame(right)+ ttk.Label(self.ai_box, text="Quality (diffusion steps)").pack(side="left")+ self.steps = tk.IntVar(value=self.s.diffusion_steps)+ ttk.Spinbox(self.ai_box, from_=2, to=12, textvariable=self.steps, width=4,+ command=self._steps_changed).pack(side="left", padx=8)+ self.del_btn = ttk.Button(self.ai_box, text="Delete voice", command=self._delete_voice)+ self.progress = ttk.Progressbar(right, mode="indeterminate", length=240)++ sb = self.sb = ttk.LabelFrame(right, text="Soundboard", padding=10)+ sb.pack(fill="both", expand=True, pady=(12, 0))+ bar = ttk.Frame(sb)+ bar.pack(fill="x")+ ttk.Button(bar, text="Choose folder…", command=self._pick_sounds).pack(side="left")+ ttk.Button(bar, text="Stop sounds", command=self.stop_sounds).pack(side="left", padx=6)+ self.sb_grid = ttk.Frame(sb)+ self.sb_grid.pack(fill="both", expand=True, pady=(8, 0))+ self._fill_soundboard()+++ # -------------------------------------------------------------- voices+ def refresh_voices(self, select: str | None = None):+ self.presets = list_presets()+ self._fill_tree()+ if select and select in self.presets:+ self.tree.selection_set(select)+ self.tree.see(select)++ def _fill_tree(self):+ q = self.search.get().lower().strip()+ self.tree.delete(*self.tree.get_children())+ groups: dict[str, str] = {}+ order = lambda k: (self.presets[k].get("category") != "my voices", self.presets[k].get("category", ""), # noqa: E731+ self.presets[k].get("name", k))+ for key in sorted(self.presets, key=order):+ spec = self.presets[key]+ if spec.get("template"):+ continue # templates are reached through "New AI voice"+ if q and q not in spec.get("name", key).lower() and q not in spec.get("category", "").lower():+ continue+ cat = spec.get("category", "other").title()+ if cat not in groups:+ groups[cat] = self.tree.insert("", "end", text=cat, open=True)+ self.tree.insert(groups[cat], "end", iid=key, text=spec.get("name", key))+ if self.current_key and self.tree.exists(self.current_key):+ self.tree.selection_set(self.current_key)++ def _on_select(self):+ sel = self.tree.selection()+ if not sel or sel[0] not in self.presets or sel[0] == self.current_key:+ return+ self.select_voice(sel[0])++ def select_voice(self, key: str):+ spec = self.presets[key]+ self.current_key = key+ self.s.voice = key+ self.s.save()+ self.v_name.config(text=spec.get("name", key))+ self.v_desc.config(text=spec.get("description", ""))+ if is_ai(spec):+ self.ai_box.pack(anchor="w", pady=4, before=self.sb)+ self.del_btn.pack(side="left", padx=12) if spec.get("_user") else self.del_btn.pack_forget()+ else:+ self.ai_box.pack_forget()+ self._load_processor(spec)++ def _load_processor(self, spec):+ if not self.engine:+ return+ self._load_token += 1+ token = self._load_token+ if not is_ai(spec):+ self._apply_processor(build_processor(spec, SR), spec)+ return+ self.progress.pack(anchor="w", pady=4, before=self.sb)+ self.progress.start(12)+ self.status.set(f"Loading {spec.get('name')}…")+ steps = int(self.steps.get()) # Tk state is read on the UI thread only++ def run():+ try:+ proc = build_processor(spec, SR, diffusion_steps=steps, ai_mode="threaded")+ proc.warmup()+ self.call_soon(lambda: token == self._load_token and self._apply_processor(proc, spec))+ except Exception as e:+ log.exception("AI voice failed to load")+ msg = str(e)+ self.call_soon(lambda: self.status.set(f"Could not load AI voice: {msg}"))+ finally:+ self.call_soon(self._stop_progress)+ threading.Thread(target=run, daemon=True).start()++ def _stop_progress(self):+ self.progress.stop()+ self.progress.pack_forget()++ def _apply_processor(self, proc, spec):+ if self.engine:+ self.engine.set_processor(proc)+ self._status_line()++ def _steps_changed(self):+ self.s.diffusion_steps = int(self.steps.get())+ self.s.save()+ if self.current_key:+ self._load_processor(self.presets[self.current_key])++ def _delete_voice(self):+ key = self.current_key+ if key and messagebox.askyesno("Delete voice", f"Delete '{self.presets[key].get('name')}'?"):+ delete_user_voice(key)+ self.current_key = None+ self.refresh_voices(select="clean")++ # -------------------------------------------------------------- engine+ def restart_engine(self):+ if self.engine:+ self.engine.stop()+ self.engine = None+ s = self.s+ try:+ monitor = s.monitor_device or self._default_monitor()+ self.engine = AudioEngine(s.input_device or None, s.output_device or "virtual", monitor,+ samplerate=SR, blocksize=512, hostapi=self.hostapi)+ self.apply_toggles(save=False)+ self.engine.start()+ self.banner.pack_forget()+ except NoVirtualCable:+ self.engine = None+ self._show_banner("No virtual microphone installed — Discord, OBS and games can't hear VoxShift yet.")+ self.status.set("Audio stopped: no virtual microphone")+ return+ except Exception as e:+ log.exception("audio engine failed to start")+ self.engine = None+ self._show_banner(f"Audio device problem: {e}", button=False)+ self.status.set("Audio stopped — check Settings")+ return+ if self.current_key:+ self._load_processor(self.presets[self.current_key])+ self._status_line()++ def _default_monitor(self) -> str | None:+ """Hear yourself on the system default output unless that is a virtual cable."""+ import sounddevice as sd+ h = next(h for h in sd.query_hostapis() if h["name"] == self.hostapi)+ if h["default_output_device"] < 0:+ return None+ name = sd.query_devices(h["default_output_device"])["name"]+ return None if any(name == c.playback for c in find_cables(self.hostapi)) else name++ def _show_banner(self, text, button=True):+ self.banner_text.config(text=text)+ self.banner_btn.pack(side="right") if button else self.banner_btn.pack_forget()+ self.banner.pack(fill="x", after=self.root.winfo_children()[0])++ def apply_toggles(self, save=True):+ s = self.s+ s.voice_enabled, s.hear_myself, s.mic_muted = self.voice_var.get(), self.hear_var.get(), self.mute_var.get()+ if self.engine:+ e = self.engine+ e.voice_enabled, e.hear_myself, e.mic_muted = s.voice_enabled, s.hear_myself, s.mic_muted+ e.input_gain_db, e.output_gain_db, e.monitor_gain_db = s.input_gain_db, s.output_gain_db, s.monitor_gain_db+ if save:+ s.save()+ self._update_tray()++ def _status_line(self):+ if not self.engine:+ return+ import sounddevice as sd+ out = sd.query_devices(self.engine.output_device)["name"]+ cable = next((c for c in find_cables(self.hostapi) if c.playback == out), None)+ mic = f"In Discord/OBS/games pick the microphone “{cable.capture}”" if cable else f"Output: {out}"+ lat = ""+ if self.engine.processor is not None:+ lat = f" · latency ≈ {1000 * self.engine.processor.latency / SR + self.engine.stream_latency_ms:.0f} ms"+ self.status.set(mic + lat)++ # -------------------------------------------------------------- virtual mic+ def install_cable(self):+ if not messagebox.askokcancel(+ "Set up virtual microphone",+ "VoxShift will download the free VB-CABLE driver from vb-audio.com, check its signature "+ "and install it.\n\nWindows will ask for permission twice (admin + driver). "+ "A restart may be needed afterwards."):+ return+ self.status.set("Installing VB-CABLE…")+ hwnd = int(self.root.wm_frame(), 16) # parent the UAC prompt to our window so it shows on top++ def run():+ try:+ install_vbcable(silent=True, hwnd=hwnd)+ ok = bool(find_cables(self.hostapi))+ msg = "Virtual microphone ready." if ok else "VB-CABLE installed — restart Windows to finish."+ except Exception as e:+ log.exception("VB-CABLE install failed")+ msg = f"VB-CABLE install failed: {e}"+ self.call_soon(lambda: (self.status.set(msg), self._after_install()))+ threading.Thread(target=run, daemon=True).start()++ def _after_install(self):+ import sounddevice as sd+ sd._terminate() # re-enumerate devices so the new endpoints appear+ sd._initialize()+ self.restart_engine()++ def test_cable(self):+ from .audio.cable import self_test+ cables = find_cables(self.hostapi)+ if not cables:+ messagebox.showinfo("Virtual microphone", "No virtual microphone installed.")+ return+ ok, ratio = self_test(cables[0], self.hostapi)+ messagebox.showinfo("Virtual microphone", f"{cables[0].label}: {'working' if ok else 'NOT passing audio'} "+ f"({ratio:.0f} dB tone-to-noise)")++ def _first_run(self):+ if self.s.first_run_done:+ return+ self.s.first_run_done = True+ self.s.save()+ if not find_cables(self.hostapi):+ self.install_cable()++ # -------------------------------------------------------------- soundboard+ def _pick_sounds(self):+ d = filedialog.askdirectory()+ if d:+ self.s.soundboard_dir = d+ self.s.save()+ self._fill_soundboard()++ def _fill_soundboard(self):+ for w in self.sb_grid.winfo_children():+ w.destroy()+ d = Path(self.s.soundboard_dir) if self.s.soundboard_dir else None+ if not d or not d.is_dir():+ ttk.Label(self.sb_grid, text="Choose a folder of sounds (wav, flac, ogg, mp3).",+ foreground="#999").grid()+ return+ files = [p for p in sorted(d.iterdir()) if p.suffix.lower() in (".wav", ".flac", ".ogg", ".mp3")]+ for i, p in enumerate(files[:30]):+ ttk.Button(self.sb_grid, text=p.stem[:18], width=18, command=lambda p=p: self.play(p)).grid(+ row=i // 4, column=i % 4, sticky="ew", padx=3, pady=3)++ def play(self, path: Path):+ import soundfile as sf+ if self.engine:+ data, sr = sf.read(str(path), dtype="float32")+ self.engine.play_sound(data, sr)++ def stop_sounds(self):+ if self.engine:+ self.engine.stop_sounds()++ # -------------------------------------------------------------- hotkeys / tray+ def register_hotkeys(self):+ if self.hotkeys:+ self.hotkeys.stop()+ actions = {"toggle_voice": lambda: self._flip(self.voice_var),+ "toggle_hear_myself": lambda: self._flip(self.hear_var),+ "toggle_mute": lambda: self._flip(self.mute_var),+ "stop_sounds": self.stop_sounds}+ bindings = {k: (spec, (lambda a=actions[k]: self.call_soon(a)))+ for k, spec in self.s.hotkeys.items() if spec and k in actions}+ self.hotkeys = winsys.GlobalHotkeys(bindings)+ self.hotkey_errors = dict(self.hotkeys.failed)+ for k, err in self.hotkey_errors.items():+ log.warning("hotkey %s: %s", k, err)++ def _flip(self, var: tk.BooleanVar):+ var.set(not var.get())+ self.apply_toggles()++ def _start_tray(self):+ try:+ import pystray+ from PIL import Image+ except ImportError:+ return+ item = pystray.MenuItem+ ui = lambda f: (lambda icon, it: self.call_soon(f)) # noqa: E731+ menu = pystray.Menu(+ item("Open VoxShift", ui(self.show), default=True),+ # pystray evaluates `checked` on its own thread: read plain settings, never Tk variables+ item("Voice changer", ui(lambda: self._flip(self.voice_var)), checked=lambda it: self.s.voice_enabled),+ item("Hear myself", ui(lambda: self._flip(self.hear_var)), checked=lambda it: self.s.hear_myself),+ item("Mute mic", ui(lambda: self._flip(self.mute_var)), checked=lambda it: self.s.mic_muted),+ pystray.Menu.SEPARATOR,+ item("Quit", ui(self.quit)))+ self.tray = pystray.Icon("VoxShift", Image.open(ASSETS / "voxshift.png"), "VoxShift", menu)+ self.tray.run_detached()++ def _update_tray(self):+ if self.tray:+ self.tray.update_menu()++ def show(self):+ self.root.deiconify()+ self.root.lift()+ self.root.focus_force()++ def on_close(self):+ if self.s.close_to_tray and self.tray:+ self.root.withdraw()+ if not getattr(self, "_told_tray", False):+ self._told_tray = True+ self.tray.notify("VoxShift keeps running in the tray. Right-click the icon to quit.", "VoxShift")+ else:+ self.quit()++ def quit(self):+ self.s.save()+ if self.hotkeys:+ self.hotkeys.stop()+ if self.engine:+ self.engine.stop()+ if self.tray:+ self.tray.stop()+ self.root.destroy()++ # -------------------------------------------------------------- threading+ def call_soon(self, fn):+ """Run ``fn`` on the Tk thread. Safe from any thread (Tk itself is not)."""+ self._ui_queue.put(fn)++ # -------------------------------------------------------------- meters+ def _tick(self):+ while not self._ui_queue.empty():+ try:+ self._ui_queue.get_nowait()()+ except Exception:+ log.exception("UI callback failed")+ c = self.meter+ c.delete("all")+ if self.engine:+ for i, db in enumerate((self.engine.meters.input_db, self.engine.meters.output_db)):+ frac = max(0.0, min(1.0, (db + 60) / 60))+ c.create_rectangle(0, 3 + i * 12, 160 * frac, 11 + i * 12,+ fill="#22c55e" if frac < 0.85 else "#ef4444", width=0)+ self.root.after(60, self._tick)+++# ---------------------------------------------------------------------- entry+def _setup_logging():+ path = log_dir() / "voxshift.log"+ handler = logging.handlers.RotatingFileHandler(path, maxBytes=2_000_000, backupCount=2, encoding="utf-8")+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))+ logging.basicConfig(level=logging.INFO, handlers=[handler])+ if FROZEN and sys.stdout is None: # windowed build: no console to print to+ sys.stdout = sys.stderr = open(path.with_name("stdout.log"), "a", encoding="utf-8", buffering=1)+ log.info("VoxShift %s starting", __version__)+++def main(argv: list[str] | None = None):+ argv = sys.argv[1:] if argv is None else argv+ _setup_logging()+ guard = winsys.SingleInstance()+ if guard.already_running:+ winsys.message_box("VoxShift is already running — look for its icon in the system tray.")+ return+ winsys.set_app_id()+ winsys.enable_dpi_awareness()+ root = tk.Tk()++ def report(exc, val, tb):+ log.error("unhandled UI error", exc_info=(exc, val, tb))+ messagebox.showerror("VoxShift", f"{exc.__name__}: {val}\n\nDetails were written to {log_dir()}")+ root.report_callback_exception = report+ App(root, minimized="--minimized" in argv)+ root.mainloop()+++if __name__ == "__main__":+ main()diff --git a/voxshift/paths.py b/voxshift/paths.pynew file mode 100644index 0000000..c556f57--- /dev/null+++ b/voxshift/paths.py@@ -0,0 +1,50 @@+"""Where VoxShift keeps things, in a source checkout and in the frozen app.++Program files (read-only, replaced on update) are kept apart from per-user+data in %APPDATA% (settings, your own voices, logs).+"""+from __future__ import annotations++import os+import sys+from pathlib import Path++APP_NAME = "VoxShift"+FROZEN = bool(getattr(sys, "frozen", False))+++def install_dir() -> Path:+ """Folder holding the executable (frozen) or the repository root (source)."""+ if FROZEN:+ return Path(sys.executable).resolve().parent+ return Path(__file__).resolve().parent.parent+++def models_dir() -> Path:+ return install_dir() / "models"+++def data_dir() -> Path:+ base = os.environ.get("APPDATA") or str(Path.home() / ".config")+ d = Path(base) / APP_NAME+ d.mkdir(parents=True, exist_ok=True)+ return d+++def user_voices_dir() -> Path:+ d = data_dir() / "voices"+ d.mkdir(parents=True, exist_ok=True)+ return d+++def references_dir() -> Path:+ """Reference recordings behind the user's own AI voices."""+ d = data_dir() / "references"+ d.mkdir(parents=True, exist_ok=True)+ return d+++def log_dir() -> Path:+ d = data_dir() / "logs"+ d.mkdir(parents=True, exist_ok=True)+ return ddiff --git a/voxshift/presets.py b/voxshift/presets.pynew file mode 100644index 0000000..7c366c3--- /dev/null+++ b/voxshift/presets.py@@ -0,0 +1,106 @@+"""Voice preset discovery and processor construction (DSP graph or AI)."""+from __future__ import annotations++import importlib.util+import json+import re+import shutil+from pathlib import Path++from .dsp.graph import Voice+from .paths import models_dir, references_dir, user_voices_dir++BUILTIN_DIR = Path(__file__).resolve().parent / "voices"+ONNX_MODEL = "whisper-small-bigvgan"+++def preset_dirs() -> list[Path]:+ return [BUILTIN_DIR, user_voices_dir()]+++def is_ai(spec: dict) -> bool:+ return spec.get("engine") == "seedvc"+++def unavailable_reason(spec: dict) -> str | None:+ """Why a voice cannot run in this installation (None = it can)."""+ if not is_ai(spec):+ return None+ if spec.get("backend") == "onnx":+ d = models_dir() / "onnx" / spec.get("model", ONNX_MODEL)+ return None if (d / "config.json").is_file() else "AI model files are not installed"+ if importlib.util.find_spec("torch") is None:+ return "needs the PyTorch developer setup"+ return None+++def list_presets(include_unavailable: bool = False) -> dict[str, dict]:+ found: dict[str, dict] = {}+ for d in preset_dirs():+ if not d.is_dir():+ continue+ for p in sorted(d.glob("*.json")):+ try:+ spec = json.loads(p.read_text(encoding="utf-8"))+ except ValueError:+ continue+ spec["_path"] = str(p)+ spec["_user"] = d != BUILTIN_DIR+ if include_unavailable or unavailable_reason(spec) is None:+ found[p.stem] = spec+ return found+++def load_spec(name_or_path: str) -> dict:+ p = Path(name_or_path)+ if p.suffix == ".json" and p.is_file():+ spec = json.loads(p.read_text(encoding="utf-8"))+ spec["_path"] = str(p)+ return spec+ presets = list_presets(include_unavailable=True)+ if name_or_path not in presets:+ raise KeyError(f"voice {name_or_path!r} not found; available: {', '.join(presets)}")+ return presets[name_or_path]+++def create_ai_voice(name: str, reference: str, base: str = "ai-whisper-small-onnx") -> str:+ """Save a personal AI voice ("Voicelab"): copy the reference recording into+ the user data folder and write a preset pointing at it. Returns its key."""+ slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") or "voice"+ key = f"my-{slug}"+ ref = Path(reference)+ dest = references_dir() / f"{key}{ref.suffix.lower() or '.wav'}"+ if ref.resolve() != dest.resolve():+ shutil.copyfile(ref, dest)+ spec = {k: v for k, v in load_spec(base).items() if not k.startswith("_") and k != "template"}+ spec.update({"name": name, "category": "my voices", "reference": str(dest),+ "description": f"Your AI voice from {ref.name}."})+ (user_voices_dir() / f"{key}.json").write_text(json.dumps(spec, indent=2, ensure_ascii=False), encoding="utf-8")+ return key+++def delete_user_voice(key: str) -> None:+ spec = load_spec(key)+ if not spec.get("_user"):+ raise ValueError("built-in voices cannot be deleted")+ ref = spec.get("reference")+ if ref and Path(ref).parent == references_dir():+ Path(ref).unlink(missing_ok=True)+ Path(spec["_path"]).unlink(missing_ok=True)+++def build_processor(spec: dict, sr: int, *, reference: str | None = None,+ ai_mode: str = "inline", device: str | None = None, **overrides):+ """Return an object with ``process(np.ndarray) -> np.ndarray`` and ``latency``."""+ if is_ai(spec):+ reason = unavailable_reason(spec)+ if reason:+ raise RuntimeError(f"{spec.get('name')}: {reason}")+ from .ai.seedvc import SeedVCProcessor # heavy import, only when needed+ spec = {**spec, **{k: v for k, v in overrides.items() if v is not None}}+ if reference:+ spec["reference"] = reference+ if not spec.get("reference"):+ raise ValueError("AI voices need a reference recording of the target voice (--reference file.wav)")+ return SeedVCProcessor(spec, sr, mode=ai_mode, device=device)+ return Voice(spec, sr)diff --git a/voxshift/settings.py b/voxshift/settings.pynew file mode 100644index 0000000..78711d0--- /dev/null+++ b/voxshift/settings.py@@ -0,0 +1,52 @@+"""Persistent user settings (%APPDATA%\\VoxShift\\settings.json)."""+from __future__ import annotations++import json+from dataclasses import asdict, dataclass, field, fields++from .paths import data_dir+++@dataclass+class Settings:+ input_device: str = ""+ output_device: str = "virtual"+ monitor_device: str = ""+ voice: str = "clean"+ voice_enabled: bool = True+ hear_myself: bool = False+ mic_muted: bool = False+ input_gain_db: float = 0.0+ output_gain_db: float = 0.0+ monitor_gain_db: float = -6.0+ diffusion_steps: int = 6+ soundboard_dir: str = ""+ start_minimized: bool = False+ close_to_tray: bool = True+ first_run_done: bool = False+ hotkeys: dict = field(default_factory=lambda: {+ "toggle_voice": "ctrl+alt+f9",+ "toggle_hear_myself": "ctrl+alt+f10",+ "toggle_mute": "ctrl+alt+f11",+ "stop_sounds": "ctrl+alt+f12",+ })++ @classmethod+ def path(cls):+ return data_dir() / "settings.json"++ @classmethod+ def load(cls) -> "Settings":+ try:+ raw = json.loads(cls.path().read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return cls()+ known = {f.name for f in fields(cls)}+ s = cls(**{k: v for k, v in raw.items() if k in known})+ s.hotkeys = {**cls().hotkeys, **(s.hotkeys or {})}+ return s++ def save(self) -> None:+ tmp = self.path().with_suffix(".tmp")+ tmp.write_text(json.dumps(asdict(self), indent=2), encoding="utf-8")+ tmp.replace(self.path())diff --git a/voxshift/voices/ai-realtime.json b/voxshift/voices/ai-realtime.jsonnew file mode 100644index 0000000..0eebe31--- /dev/null+++ b/voxshift/voices/ai-realtime.json@@ -0,0 +1,17 @@+{+ "category": "ai",+ "engine": "seedvc",+ "reference": "",+ "inference_cfg_rate": 0.7,+ "crossfade_time": 0.04,+ "extra_time_ce": 2.5,+ "extra_time": 0.5,+ "extra_time_right": 0.02,+ "max_prompt_length": 3.0,+ "silence_threshold_db": -55,+ "name": "AI Voice (XLSR-tiny + HiFT, fastest)",+ "description": "Lower-latency Seed-VC real-time model (wav2vec2-XLSR content features, HiFT vocoder).",+ "model": "xlsr-tiny-hifigan",+ "diffusion_steps": 6,+ "block_time": 0.2+}diff --git a/voxshift/voices/ai-whisper-small-onnx.json b/voxshift/voices/ai-whisper-small-onnx.jsonnew file mode 100644index 0000000..c87672c--- /dev/null+++ b/voxshift/voices/ai-whisper-small-onnx.json@@ -0,0 +1,20 @@+{+ "category": "ai",+ "engine": "seedvc",+ "reference": "",+ "inference_cfg_rate": 0.7,+ "crossfade_time": 0.04,+ "extra_time_ce": 2.5,+ "extra_time": 0.5,+ "extra_time_right": 0.02,+ "max_prompt_length": 3.0,+ "silence_threshold_db": -55,+ "name": "AI voice (template)",+ "description": "Template for your own AI voices: Whisper-small encoder -> DiT flow matching -> BigVGAN, run by ONNX Runtime (DirectML > CUDA > CPU).",+ "model": "whisper-small-bigvgan",+ "diffusion_steps": 6,+ "block_time": 0.5,+ "backend": "onnx",+ "onnx_dir": "models/onnx/whisper-small-bigvgan",+ "template": true+}diff --git a/voxshift/voices/ai-whisper-small.json b/voxshift/voices/ai-whisper-small.jsonnew file mode 100644index 0000000..c3c0cf1--- /dev/null+++ b/voxshift/voices/ai-whisper-small.json@@ -0,0 +1,17 @@+{+ "category": "ai",+ "engine": "seedvc",+ "reference": "",+ "inference_cfg_rate": 0.7,+ "crossfade_time": 0.04,+ "extra_time_ce": 2.5,+ "extra_time": 0.5,+ "extra_time_right": 0.02,+ "max_prompt_length": 3.0,+ "silence_threshold_db": -55,+ "name": "AI Voice (Whisper-small + BigVGAN)",+ "description": "Zero-shot voice conversion (Seed-VC): Whisper encoder -> DiT flow matching -> BigVGAN vocoder.",+ "model": "whisper-small-bigvgan",+ "diffusion_steps": 8,+ "block_time": 0.3+}diff --git a/voxshift/voices/alien.json b/voxshift/voices/alien.jsonnew file mode 100644index 0000000..434b628--- /dev/null+++ b/voxshift/voices/alien.json@@ -0,0 +1,37 @@+{+ "name": "Alien",+ "category": "monster",+ "description": "Wobbling pitch, ring-mod shimmer and chorus.",+ "chain": [+ {+ "type": "FormantPitchShifter",+ "params": {+ "semitones": {+ "lfo": {+ "rate": 3.0,+ "min": 2.0,+ "max": 5.0+ }+ },+ "formant_semitones": 3+ }+ },+ {+ "type": "RingModulation",+ "params": {+ "freq": 320,+ "mix": 0.3+ }+ },+ {+ "type": "ModDelay",+ "params": {+ "base_ms": 12,+ "depth_ms": 5,+ "rate_hz": 1.2,+ "voices": 3,+ "mix": 0.5+ }+ }+ ]+}diff --git a/voxshift/voices/autotune.json b/voxshift/voices/autotune.jsonnew file mode 100644index 0000000..77efe9c--- /dev/null+++ b/voxshift/voices/autotune.json@@ -0,0 +1,15 @@+{+ "name": "Auto-Tune",+ "category": "music",+ "description": "Hard pitch correction to the chromatic scale.",+ "chain": [+ {+ "type": "FormantPitchShifter",+ "params": {+ "autotune": 1.0,+ "autotune_speed": 1.0,+ "scale": "chromatic"+ }+ }+ ]+}diff --git a/voxshift/voices/baby.json b/voxshift/voices/baby.jsonnew file mode 100644index 0000000..7d6f552--- /dev/null+++ b/voxshift/voices/baby.json@@ -0,0 +1,14 @@+{+ "name": "Baby",+ "category": "pitch",+ "description": "Very high pitch with small vocal tract.",+ "chain": [+ {+ "type": "FormantPitchShifter",+ "params": {+ "semitones": 9,+ "formant_semitones": 4+ }+ }+ ]+}diff --git a/voxshift/voices/cave.json b/voxshift/voices/cave.jsonnew file mode 100644index 0000000..bbd9301--- /dev/null+++ b/voxshift/voices/cave.json@@ -0,0 +1,24 @@+{+ "name": "Cave",+ "category": "space",+ "description": "Long dark reverb with slapback echoes.",+ "chain": [+ {+ "type": "Delay",+ "params": {+ "time_ms": 320,+ "feedback": 0.3,+ "mix": 0.35+ }+ },+ {+ "type": "ConvolutionReverb",+ "params": {+ "decay_s": 3.2,+ "predelay_ms": 40,+ "damping": 0.75,+ "mix": 0.45+ }+ }+ ]+}diff --git a/voxshift/voices/chipmunk.json b/voxshift/voices/chipmunk.jsonnew file mode 100644index 0000000..799da64--- /dev/null+++ b/voxshift/voices/chipmunk.json@@ -0,0 +1,14 @@+{+ "name": "Chipmunk",+ "category": "pitch",+ "description": "High pitch, formants shifted with it.",+ "chain": [+ {+ "type": "FormantPitchShifter",+ "params": {+ "semitones": 8,+ "preserve_formants": false+ }+ }+ ]+}diff --git a/voxshift/voices/clean.json b/voxshift/voices/clean.jsonnew file mode 100644index 0000000..581c836--- /dev/null+++ b/voxshift/voices/clean.json@@ -0,0 +1,6 @@+{+ "name": "Clean",+ "category": "utility",+ "description": "Passthrough (no effect).",+ "chain": []+}diff --git a/voxshift/voices/dalek.json b/voxshift/voices/dalek.jsonnew file mode 100644index 0000000..6ed5158--- /dev/null+++ b/voxshift/voices/dalek.json@@ -0,0 +1,36 @@+{+ "name": "Dalek",+ "category": "robot",+ "description": "30 Hz ring modulator, crunchy and band-limited.",+ "chain": [+ {+ "type": "RingModulation",+ "params": {+ "freq": 30,+ "mix": 1.0+ }+ },+ {+ "type": "Distortion",+ "params": {+ "drive_db": 10,+ "shape": "tanh",+ "output_db": -4+ }+ },+ {+ "type": "Biquad",+ "params": {+ "kind": "bandpass",+ "freq": 1200,+ "q": 0.6+ }+ },+ {+ "type": "Gain",+ "params": {+ "gain_db": 6+ }+ }+ ]+}diff --git a/voxshift/voices/deep.json b/voxshift/voices/deep.jsonnew file mode 100644index 0000000..f66fb53--- /dev/null+++ b/voxshift/voices/deep.json@@ -0,0 +1,23 @@+{+ "name": "Deep",+ "category": "pitch",+ "description": "Lower pitch with natural formants.",+ "chain": [+ {+ "type": "FormantPitchShifter",+ "params": {+ "semitones": -5,+ "formant_semitones": -1.5+ }+ },+ {+ "type": "Biquad",+ "params": {+ "kind": "lowshelf",+ "freq": 200,+ "q": 0.7,+ "gain_db": 3+ }+ }+ ]+}diff --git a/voxshift/voices/demon.json b/voxshift/voices/demon.jsonnew file mode 100644index 0000000..4f530ff--- /dev/null+++ b/voxshift/voices/demon.json@@ -0,0 +1,51 @@+{+ "name": "Demon",+ "category": "monster",+ "description": "Octave-down layered with a fifth-down, distorted, in a hall.",+ "chain": [+ {+ "type": "Parallel",+ "gains_db": [+ 0,+ -4+ ],+ "branches": [+ [+ {+ "type": "FormantPitchShifter",+ "params": {+ "semitones": -12,+ "formant_semitones": -5+ }+ }+ ],+ [+ {+ "type": "FormantPitchShifter",+ "params": {+ "semitones": -7,+ "formant_semitones": -3+ }+ }+ ]+ ]+ },+ {+ "type": "Distortion",+ "params": {+ "drive_db": 8,+ "shape": "tanh",+ "mix": 0.6,+ "output_db": -3+ }+ },+ {+ "type": "ConvolutionReverb",+ "params": {+ "decay_s": 2.5,+ "mix": 0.3,+ "damping": 0.7+ }+ }+ ]+}diff --git a/voxshift/voices/drunk.json b/voxshift/voices/drunk.jsonnew file mode 100644index 0000000..dc6313d--- /dev/null+++ b/voxshift/voices/drunk.json@@ -0,0 +1,30 @@+{+ "name": "Drunk",+ "category": "fun",+ "description": "Pitch that wanders randomly.",+ "chain": [+ {+ "type": "PitchShift",+ "params": {+ "semitones": {+ "random": {+ "min": -3,+ "max": 2,+ "interval_s": 0.6,+ "smooth": 0.9+ }+ }+ }+ },+ {+ "type": "ModDelay",+ "params": {+ "base_ms": 8,+ "depth_ms": 6,+ "rate_hz": 0.4,+ "voices": 1,+ "mix": 0.3+ }+ }+ ]+}diff --git a/voxshift/voices/female-to-male.json b/voxshift/voices/female-to-male.jsonnew file mode 100644index 0000000..1f1c00f--- /dev/null+++ b/voxshift/voices/female-to-male.json@@ -0,0 +1,23 @@+{+ "name": "Female to Male",+ "category": "gender",+ "description": "-4 st pitch, -2.5 st formants.",+ "chain": [+ {+ "type": "FormantPitchShifter",+ "params": {+ "semitones": -4,+ "formant_semitones": -2.5+ }+ },+ {+ "type": "Biquad",+ "params": {+ "kind": "lowshelf",+ "freq": 180,+ "q": 0.7,+ "gain_db": 2+ }+ }+ ]+}diff --git a/voxshift/voices/ghost.json b/voxshift/voices/ghost.jsonnew file mode 100644index 0000000..77adb0c--- /dev/null+++ b/voxshift/voices/ghost.json@@ -0,0 +1,34 @@+{+ "name": "Ghost",+ "category": "monster",+ "description": "Whispered, pitched-up and drowned in reverb.",+ "chain": [+ {+ "type": "Whisperize"+ },+ {+ "type": "PitchShift",+ "params": {+ "semitones": 4+ }+ },+ {+ "type": "ModDelay",+ "params": {+ "base_ms": 20,+ "depth_ms": 8,+ "rate_hz": 0.25,+ "voices": 2,+ "mix": 0.5+ }+ },+ {+ "type": "ConvolutionReverb",+ "params": {+ "decay_s": 4.0,+ "mix": 0.55,+ "damping": 0.3+ }+ }+ ]+}diff --git a/voxshift/voices/giant.json b/voxshift/voices/giant.jsonnew file mode 100644index 0000000..7e01c3f--- /dev/null+++ b/voxshift/voices/giant.json@@ -0,0 +1,21 @@+{+ "name": "Giant",+ "category": "pitch",+ "description": "Huge vocal tract, low pitch, room.",+ "chain": [+ {+ "type": "FormantPitchShifter",+ "params": {+ "semitones": -9,+ "formant_semitones": -5+ }+ },+ {+ "type": "ConvolutionReverb",+ "params": {+ "decay_s": 1.8,+ "mix": 0.2+ }+ }+ ]+}diff --git a/voxshift/voices/male-to-female.json b/voxshift/voices/male-to-female.jsonnew file mode 100644index 0000000..ba754e1--- /dev/null+++ b/voxshift/voices/male-to-female.json@@ -0,0 +1,23 @@+{+ "name": "Male to Female",+ "category": "gender",+ "description": "+4 st pitch, +2.5 st formants.",+ "chain": [+ {+ "type": "FormantPitchShifter",+ "params": {+ "semitones": 4,+ "formant_semitones": 2.5+ }+ },+ {+ "type": "Biquad",+ "params": {+ "kind": "highshelf",+ "freq": 4000,+ "q": 0.7,+ "gain_db": 2+ }+ }+ ]+}diff --git a/voxshift/voices/megaphone.json b/voxshift/voices/megaphone.jsonnew file mode 100644index 0000000..8b4b5b4--- /dev/null+++ b/voxshift/voices/megaphone.json@@ -0,0 +1,40 @@+{+ "name": "Megaphone",+ "category": "device",+ "description": "Horn resonance and fuzz.",+ "chain": [+ {+ "type": "Biquad",+ "params": {+ "kind": "highpass",+ "freq": 600,+ "q": 0.7+ }+ },+ {+ "type": "Biquad",+ "params": {+ "kind": "peaking",+ "freq": 1800,+ "q": 1.2,+ "gain_db": 9+ }+ },+ {+ "type": "Distortion",+ "params": {+ "drive_db": 14,+ "shape": "fuzz",+ "output_db": -6+ }+ },+ {+ "type": "Biquad",+ "params": {+ "kind": "lowpass",+ "freq": 4500,+ "q": 0.7+ }+ }+ ]+}diff --git a/voxshift/voices/radio.json b/voxshift/voices/radio.jsonnew file mode 100644index 0000000..f424d9a--- /dev/null+++ b/voxshift/voices/radio.json@@ -0,0 +1,38 @@+{+ "name": "Radio",+ "category": "device",+ "description": "AM radio: narrow band, light crunch, static.",+ "chain": [+ {+ "type": "Biquad",+ "params": {+ "kind": "highpass",+ "freq": 450,+ "q": 0.7+ }+ },+ {+ "type": "Biquad",+ "params": {+ "kind": "lowpass",+ "freq": 3200,+ "q": 0.9+ }+ },+ {+ "type": "Distortion",+ "params": {+ "drive_db": 9,+ "shape": "tanh",+ "output_db": -2+ }+ },+ {+ "type": "Oscillator",+ "params": {+ "waveform": "noise",+ "level_db": -42+ }+ }+ ]+}diff --git a/voxshift/voices/robot.json b/voxshift/voices/robot.jsonnew file mode 100644index 0000000..9ac2011--- /dev/null+++ b/voxshift/voices/robot.json@@ -0,0 +1,33 @@+{+ "name": "Robot",+ "category": "robot",+ "description": "Channel vocoder on a saw carrier plus metallic flange.",+ "chain": [+ {+ "type": "Vocoder",+ "params": {+ "carrier_hz": 110,+ "waveform": "saw",+ "bands": 32+ }+ },+ {+ "type": "ModDelay",+ "params": {+ "base_ms": 3,+ "depth_ms": 1.5,+ "rate_hz": 0.3,+ "voices": 1,+ "mix": 0.5+ }+ },+ {+ "type": "Compressor",+ "params": {+ "threshold_db": -24,+ "ratio": 4,+ "makeup_db": 6+ }+ }+ ]+}diff --git a/voxshift/voices/stadium.json b/voxshift/voices/stadium.jsonnew file mode 100644index 0000000..b8c9002--- /dev/null+++ b/voxshift/voices/stadium.json@@ -0,0 +1,38 @@+{+ "name": "Stadium Announcer",+ "category": "space",+ "description": "PA-system tone with long slap echoes.",+ "chain": [+ {+ "type": "Biquad",+ "params": {+ "kind": "highpass",+ "freq": 250,+ "q": 0.7+ }+ },+ {+ "type": "Compressor",+ "params": {+ "threshold_db": -28,+ "ratio": 5,+ "makeup_db": 9+ }+ },+ {+ "type": "Delay",+ "params": {+ "time_ms": 180,+ "feedback": 0.45,+ "mix": 0.4+ }+ },+ {+ "type": "ConvolutionReverb",+ "params": {+ "decay_s": 2.8,+ "mix": 0.35+ }+ }+ ]+}diff --git a/voxshift/voices/telephone.json b/voxshift/voices/telephone.jsonnew file mode 100644index 0000000..f2bc377--- /dev/null+++ b/voxshift/voices/telephone.json@@ -0,0 +1,38 @@+{+ "name": "Telephone",+ "category": "device",+ "description": "Narrow-band phone line with sample-rate crush.",+ "chain": [+ {+ "type": "Biquad",+ "params": {+ "kind": "highpass",+ "freq": 300,+ "q": 0.7+ }+ },+ {+ "type": "Biquad",+ "params": {+ "kind": "lowpass",+ "freq": 3400,+ "q": 0.7+ }+ },+ {+ "type": "Bitcrusher",+ "params": {+ "bits": 10,+ "downsample": 6+ }+ },+ {+ "type": "Compressor",+ "params": {+ "threshold_db": -26,+ "ratio": 6,+ "makeup_db": 8+ }+ }+ ]+}diff --git a/voxshift/voices/whisper.json b/voxshift/voices/whisper.jsonnew file mode 100644index 0000000..f312a5d--- /dev/null+++ b/voxshift/voices/whisper.json@@ -0,0 +1,24 @@+{+ "name": "Whisper",+ "category": "fx",+ "description": "Unvoiced breathy whisper.",+ "chain": [+ {+ "type": "Whisperize"+ },+ {+ "type": "Biquad",+ "params": {+ "kind": "highpass",+ "freq": 250,+ "q": 0.7+ }+ },+ {+ "type": "Gain",+ "params": {+ "gain_db": 4+ }+ }+ ]+}diff --git a/voxshift/winsys.py b/voxshift/winsys.pynew file mode 100644index 0000000..3687524--- /dev/null+++ b/voxshift/winsys.py@@ -0,0 +1,188 @@+"""Windows integration: single instance, global hotkeys, start with Windows.++Pure ctypes / winreg, no extra dependencies. Every function degrades to a+no-op on other platforms.+"""+from __future__ import annotations++import ctypes+import sys+import threading+from ctypes import wintypes++IS_WIN = sys.platform == "win32"+RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"++_MODS = {"alt": 0x0001, "ctrl": 0x0002, "control": 0x0002, "shift": 0x0004, "win": 0x0008}+_NAMED_VK = {**{f"f{i}": 0x6F + i for i in range(1, 25)}, "space": 0x20, "tab": 0x09, "enter": 0x0D,+ "esc": 0x1B, "home": 0x24, "end": 0x23, "insert": 0x2D, "delete": 0x2E, "pause": 0x13,+ **{f"num{i}": 0x60 + i for i in range(10)}}+MOD_NOREPEAT = 0x4000+WM_HOTKEY, WM_QUIT = 0x0312, 0x0012+++def parse_hotkey(spec: str) -> tuple[int, int]:+ """'ctrl+alt+v' -> (modifiers, virtual-key)."""+ mods, vk = 0, None+ for part in spec.lower().replace(" ", "").split("+"):+ if part in _MODS:+ mods |= _MODS[part]+ elif part in _NAMED_VK:+ vk = _NAMED_VK[part]+ elif len(part) == 1 and part.isalnum():+ vk = ord(part.upper())+ else:+ raise ValueError(f"unknown key {part!r} in hotkey {spec!r}")+ if vk is None:+ raise ValueError(f"hotkey {spec!r} has no key")+ return mods, vk+++class SingleInstance:+ """Named mutex; `already_running` is True if another VoxShift holds it."""++ def __init__(self, name: str = "Local\\VoxShift.SingleInstance"):+ self.handle = None+ self.already_running = False+ if IS_WIN:+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)+ self.handle = k32.CreateMutexW(None, False, name)+ self.already_running = ctypes.get_last_error() == 183 # ERROR_ALREADY_EXISTS+++class GlobalHotkeys:+ """RegisterHotKey on a dedicated thread with its own message loop.++ Callbacks run on that thread; GUI code should marshal them back (e.g.+ ``root.after``). Keys another program already owns are reported in+ ``failed`` instead of raising.+ """++ def __init__(self, bindings: dict[str, tuple[str, callable]]):+ self.bindings = bindings # id-name -> (spec, callback)+ self.failed: dict[str, str] = {}+ self._thread_id = None+ self._ready = threading.Event()+ if IS_WIN and bindings:+ threading.Thread(target=self._loop, name="hotkeys", daemon=True).start()+ self._ready.wait(2)++ def _loop(self):+ user32, k32 = ctypes.WinDLL("user32", use_last_error=True), ctypes.WinDLL("kernel32")+ self._thread_id = k32.GetCurrentThreadId()+ actions = {}+ for i, (name, (spec, cb)) in enumerate(self.bindings.items(), start=1):+ try:+ mods, vk = parse_hotkey(spec)+ except ValueError as e:+ self.failed[name] = str(e)+ continue+ if user32.RegisterHotKey(None, i, mods | MOD_NOREPEAT, vk):+ actions[i] = cb+ else:+ self.failed[name] = f"{spec} is already used by another program"+ self._ready.set()+ msg = wintypes.MSG()+ while user32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0:+ if msg.message == WM_HOTKEY and msg.wParam in actions:+ try:+ actions[msg.wParam]()+ except Exception: # a failing action must not kill the hotkey thread+ import logging+ logging.getLogger(__name__).exception("hotkey action failed")+ for i in actions:+ user32.UnregisterHotKey(None, i)++ def stop(self):+ if IS_WIN and self._thread_id:+ ctypes.WinDLL("user32").PostThreadMessageW(self._thread_id, WM_QUIT, 0, 0)+++def autostart_command() -> str:+ from .paths import FROZEN, install_dir+ if FROZEN:+ return f'"{install_dir() / "VoxShift.exe"}" --minimized'+ return f'"{sys.executable.replace("python.exe", "pythonw.exe")}" -m voxshift gui --minimized'+++def get_autostart(name: str = "VoxShift") -> bool:+ if not IS_WIN:+ return False+ import winreg+ try:+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_KEY) as k:+ winreg.QueryValueEx(k, name)+ return True+ except OSError:+ return False+++def set_autostart(enabled: bool, name: str = "VoxShift") -> None:+ if not IS_WIN:+ return+ import winreg+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_KEY, 0, winreg.KEY_SET_VALUE) as k:+ if enabled:+ winreg.SetValueEx(k, name, 0, winreg.REG_SZ, autostart_command())+ else:+ try:+ winreg.DeleteValue(k, name)+ except FileNotFoundError:+ pass+++def set_app_id(app_id: str = "VoxShift.App") -> None:+ """Own taskbar identity/icon instead of python.exe's."""+ if IS_WIN:+ ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(app_id)+++class _SHELLEXECUTEINFOW(ctypes.Structure):+ _fields_ = [("cbSize", wintypes.DWORD), ("fMask", ctypes.c_ulong), ("hwnd", wintypes.HWND),+ ("lpVerb", wintypes.LPCWSTR), ("lpFile", wintypes.LPCWSTR), ("lpParameters", wintypes.LPCWSTR),+ ("lpDirectory", wintypes.LPCWSTR), ("nShow", ctypes.c_int), ("hInstApp", wintypes.HINSTANCE),+ ("lpIDList", ctypes.c_void_p), ("lpClass", wintypes.LPCWSTR), ("hkeyClass", wintypes.HKEY),+ ("dwHotKey", wintypes.DWORD), ("hIconOrMonitor", wintypes.HANDLE), ("hProcess", wintypes.HANDLE)]+++def run_elevated(path: str, params: str = "", hwnd: int | None = None) -> int:+ """Run ``path`` as administrator and wait; returns its exit code.++ Requesting elevation from our own (foreground) process, parented to our+ window, makes Windows show the UAC prompt on top. A hidden helper process+ only gets a flashing taskbar button, and the prompt times out unseen.+ Raises PermissionError when the user declines.+ """+ if not IS_WIN:+ raise OSError("elevation is Windows-only")+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)+ shell32 = ctypes.WinDLL("shell32", use_last_error=True)+ info = _SHELLEXECUTEINFOW(cbSize=ctypes.sizeof(_SHELLEXECUTEINFOW), fMask=0x00000040, # NOCLOSEPROCESS+ hwnd=hwnd, lpVerb="runas", lpFile=str(path), lpParameters=params or None,+ lpDirectory=str(__import__("pathlib").Path(path).parent), nShow=1)+ if not shell32.ShellExecuteExW(ctypes.byref(info)):+ err = ctypes.get_last_error()+ if err == 1223: # ERROR_CANCELLED+ raise PermissionError("administrator permission was declined")+ raise ctypes.WinError(err)+ try:+ k32.WaitForSingleObject(info.hProcess, 0xFFFFFFFF)+ code = wintypes.DWORD()+ k32.GetExitCodeProcess(info.hProcess, ctypes.byref(code))+ return code.value+ finally:+ k32.CloseHandle(info.hProcess)+++def enable_dpi_awareness() -> None:+ """Crisp rendering on scaled displays (call before creating the Tk root)."""+ if IS_WIN:+ try:+ ctypes.windll.shcore.SetProcessDpiAwareness(2) # per-monitor+ except (AttributeError, OSError):+ ctypes.windll.user32.SetProcessDPIAware()+++def message_box(text: str, title: str = "VoxShift") -> None:+ if IS_WIN:+ ctypes.windll.user32.MessageBoxW(None, text, title, 0x40)