├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── doc.md ├── examples ├── neg-adsr-env-example.lua ├── sample-project.lua ├── sample-synth-adsr-lv2fx-example.lua └── stream.lua ├── project.lua ├── project.toml ├── src ├── adsr.rs ├── bufferbank.rs ├── config.rs ├── extensions.rs ├── floww.rs ├── graph.rs ├── lv2.rs ├── main.rs ├── sample.rs ├── state.rs ├── stream_workflow.rs ├── synth.rs └── ui_workflow.rs └── test_stream.sh /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | *.wav 12 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "termdaw" 3 | version = "0.1.0" 4 | authors = ["Cody Bloemhard "] 5 | edition = "2021" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [features] 10 | # default = ["lv2"] 11 | lv2 = ["dep:lv2-host-minimal"] 12 | 13 | [dependencies] 14 | mlua = { version = "0.9.8", features = ["lua53", "vendored"] } 15 | hound = "3.5.1" 16 | rubato = "0.15.0" 17 | toml = "0.8.13" 18 | serde = { version = "1.0.202", features = ["derive"] } 19 | skim = "0.10.4" 20 | sdl2 = "0.36.0" 21 | lv2-host-minimal = { version = "0.1.4", optional = true } 22 | fnrs = "0.1.6" 23 | sampsyn = "0.1.4" 24 | floww = "0.1.10" 25 | term-basics-linux = "1.0.0" 26 | zen-colour = "1.1.1" 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # termdaw 2 | 3 | A daw, in a terminal. 4 | Termdaw is a (or should become a) terminal, graph based programmable pipeline 5 | digital audio workstation that is friendly to automatization and algorithmic composition. 6 | 7 | ## MVP Goals 8 | 9 | - Audio 10 | - [x] Render audio 11 | - Any samplerate: will up or down sample from project rate 12 | - 8, 16, 24 or 32 bit bitdepth 13 | - [x] Play back audio 14 | - Terminal UX Workflow 15 | - [x] Controls: play, pause, stop 16 | - [x] Controls: set/get time, dash in time 17 | - [x] Controls: refresh, render 18 | - [x] View: Terminal logging, warnings, errors, colors 19 | - [x] Toml configuration 20 | - Streaming Workflow 21 | - [x] Streaming mode (input through stdin) 22 | - Structure 23 | - [x] Sample Bank 24 | - [x] Floww Bank 25 | - [x] Graph rendering structure 26 | - Base Vertex, with: 27 | - [x] Gain 28 | - [x] Panning 29 | - [x] Input summation 30 | - Vertex types 31 | - [x] Sum vertex 32 | - [x] Normalize vertex 33 | - [x] Sample loop vertex 34 | - [x] Envelope vertex 35 | - [x] Sample multi vertex 36 | - [x] Sample lerp vertex 37 | - [x] Lv2 fx vertex 38 | - [ ] Lv2 midi instrument vertex 39 | - [x] Debug Sine synth vertex 40 | - [x] Simple synth vertex 41 | - [x] Wavetable synth vertex 42 | - [x] Band pass/cut vertex 43 | - Floww 44 | - [x] Read from midi 45 | - [ ] Read floww from floww description 46 | - [x] Read binary floww from stdin stream 47 | - [ ] Read human readable floww from stdin stream 48 | - Lua 49 | - [x] To configure the project (sample rate, etc) 50 | - [x] Load resources (samples and plugins) 51 | - [x] Construct graph 52 | - [x] Refreshable: remove old, add new, keep same 53 | - Docs 54 | - [x] Config documentation 55 | - [x] Examples 56 | 57 | ## Goals for later 58 | 59 | - [ ] Multitype graph 60 | - [ ] In/Out ports 61 | - [ ] Type checker 62 | - [ ] Stereo type 63 | - [ ] Mono type 64 | - [ ] Floww type 65 | - [ ] Value type 66 | - [ ] Value automation 67 | - [ ] Lufs mastering tool 68 | - [ ] Linear interpolation of floww notes 69 | - [ ] Better scrolling through time handling of on/off notes 70 | - [ ] Split vertex 71 | - [ ] Active toggle on vertices 72 | - [ ] Disable completely dry vertices 73 | - [ ] Prune disabled vertices from the graph 74 | - [ ] Multithreading 75 | - [ ] Bounded normalization in absence of the lv2 feature 76 | 77 | ## Failed 78 | 79 | - [ ] Bounded normalization: lv2 plugin's output can have more gain than input, no way to know how much. 80 | 81 | ## Example 82 | 83 | ```toml 84 | [project] 85 | name = "Example Project" 86 | 87 | [settings] 88 | buffer_length = 1024 89 | project_samplerate = 48000 90 | main = "project.lua" 91 | ``` 92 | 93 | ```lua 94 | -- Our lua file, where we do all the work 95 | set_length(3.0); 96 | set_render_samplerate(44100); 97 | set_render_bitdepth(16); 98 | set_output_file("outp.wav"); 99 | 100 | load_sample("snare", "/home/cody/doc/samples/drumnbass/snare-1/snare-1-v-9.wav"); 101 | load_sample("kick", "/home/cody/doc/samples/drumnbass/kick/kick-v-9.wav"); 102 | 103 | add_sampleloop("one", 1.0, 0.0, "snare"); 104 | add_sampleloop("two", 1.0, 0.0, "kick"); 105 | add_normalize("sum", 1.0, 0.0); 106 | 107 | connect("one", "sum"); 108 | connect("two", "sum"); 109 | 110 | set_output("sum"); 111 | ``` 112 | 113 | ## License 114 | 115 | ``` 116 | Copyright (C) 2024 Cody Bloemhard 117 | 118 | This program is free software: you can redistribute it and/or modify 119 | it under the terms of the GNU General Public License as published by 120 | the Free Software Foundation, either version 3 of the License, or 121 | (at your option) any later version. 122 | 123 | This program is distributed in the hope that it will be useful, 124 | but WITHOUT ANY WARRANTY; without even the implied warranty of 125 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 126 | GNU General Public License for more details. 127 | 128 | You should have received a copy of the GNU General Public License 129 | along with this program. If not, see . 130 | ``` 131 | -------------------------------------------------------------------------------- /doc.md: -------------------------------------------------------------------------------- 1 | # TermDaw documentation 2 | 3 | ## Config 4 | 5 | ### General 6 | 7 | The config is written as a `.toml` file. 8 | It is read on startup and can't be refreshed. 9 | If you change something you have to change termdaw again. 10 | The config is project wide, you'll have a config for every project. 11 | The config file is named `project.toml` and TermDaw will look for it in the directory it's been launched in, if no cli arguments are given. 12 | You can give one cli argument, a directory, which will become the working directory in which is will look for the .toml file and to which the main lua file is relative. 13 | 14 | ### Example 15 | 16 | ```toml 17 | [project] 18 | name = "Example Project" 19 | 20 | [settings] 21 | main = "project.lua" 22 | buffer_length = 1024 23 | project_samplerate = 48000 24 | ``` 25 | 26 | ### Fields 27 | 28 | Field | Parent | Optional | Type | Default Value 29 | ------------------------|---------------|---------------|-------|--------------- 30 | name | [project] | Yes | String| unnamed 31 | main | [settings] | No | String| 32 | buffer_length | [settings] | Yes | Uint | 1024 33 | project_samplerate | [settings] | Yes | Uint | 44100 34 | workflow | [settings] | Yes | String| manual 35 | 36 | ## Tui 37 | 38 | ### General 39 | 40 | TermDaw is controlled by a TUI (Terminal User Interface). 41 | You can select commands with the arrow keys or you can type them (partially). 42 | 43 | ## Commands 44 | - quit: close down TermDaw. 45 | - refresh: reload the lua file and update internals to match it 46 | - render: render audio and write it to disk 47 | - normalize: perform normalization scan 48 | - play: start playing audio from the current time on 49 | - pause: stop playing audio but keep current time 50 | - stop: stop playing audio and set time to 0 51 | - skip: go 5 seconds forward in time 52 | - prev: go 5 seconds backwards in time 53 | - set: prompts you for a time (float) and will set the time to it if valid 54 | - get: get the current time 55 | 56 | ## Lua 57 | 58 | ### General 59 | 60 | The project itself is configured with 61 | 62 | ### Functions 63 | 64 | #### Loading 65 | 66 | - `set_length(seconds: float);` Sets the lenght of the render in seconds. You can listen past this point in the daw. 67 | - `set_render_samplerate(sr: uint);` Sets the samplerate of the render. This is different than the samplerate of the project (internal, playback in daw, etc). You can set the project samplerate in the toml config. 68 | - `set_output_file(file: string);` Sets the name of the rendered file. 69 | - `load_sample(name: string, path: string, mode: string);` Load a sample(.wav) found at the given path into the samplebank tagged with a name for further use. Mode is the loading mode, can be left empty for standard. Modes include: 70 | - `left`: copy left channel to right channel 71 | - `right`: copy right channel to left channel 72 | - `loudest`: copy the loudest channel to the less loud channel 73 | - `normalize-seperate`: normalize each channel seperately 74 | - `mix-down`: sum both channels and copy result to both 75 | - `load_midi_floww(name: string, path: string);` Load a midi file found at the given path into the flowwbank tagged with a name for further use. 76 | - `load_lv2(name: string, uri: string);` Load a lv2 fx plugin found with the lv2 plugin URI and tag it with a name for further use. You can find all your lv2 plugins URI's with the cli program `lv2ls`. 77 | 78 | #### Misc 79 | 80 | - `parameter(plugin: string, name: string, value: float);` Set a parameter of a lv2 plugin where plugin is the name of the loaded plugin, name is the name of the parameter and the value what to assign it to. 81 | 82 | #### Graph 83 | 84 | ##### Vertex 85 | 86 | Every vertex has a: 87 | - name: name of the vertex to reference it by 88 | - gain: the volume of the vertex, can be over one 89 | - angle: the angle of panning of the vertex. `0.0` is in the middle, `90.0` is full left and `-90.0` is full right. 90 | 91 | ##### Adsr Config 92 | A adsr conf describes the amplitude of a sound over time (Attack, Decay, Sustain, Release). 93 | The release part is used when the note is released according to the floww. 94 | You contruct an adsr conf as an array of floats. You can either have 6 or 9 floats in it representing (attack_seconds, decay_seconds, decay_velocity, sustain_seconds, sustain_velocity, release_seconds) and (standard_velocity, attack_seconds, attack_velocity, decay_seconds, decay_velocity, sustain_seconds, sustain_velocity, release_seconds, release_velocity) respectively. The seconds are how long those parts last and the velocities are how loud the note is at that time. For a better understanding see [wikipedia](https://en.wikipedia.org/wiki/Envelope_(music)). 95 | 96 | - `add_sum(name: string, gain: float, angle: float);` Add a summing vertex. It takes all inputs and sums them together. 97 | - `add_normalize(name: string, gain: float, angle: float);` Add a normalize vertex. It takes all inputs and sums them, then normalizes the signal to be inbetween zero and one. So find out the mulitplier it has to use, you need to run the `normalize` command. You can let it do the normalize scan every refresh or not (see toml config). If somehow after some changes the audio distorts at the peaks, you need to can again. 98 | - `add_sampleloop(name: string, gain: float, angle: float, sample: string);` take the sample by name and just loop it. 99 | - `add_sample_multi(name: string, gain: float, angle: float, sample: string, floww: string, note: int);` Add a vertex that plays a sample when a note hits in a floww. 100 | - You can configure a specific midi note value that it will trigger on with the note argument. If you set it to -1 it will trigger on any note. 101 | - This vertex can play samples in parallel, if a note hits and the old one was not yet done both will play. 102 | - `add_sample_lerp(name: string, gain: float, angle: float, sample: string, floww: string, note: int, lerp_length: int);` Add a vertex that plays a sample when a note hits in a floww. 103 | - You can configure a specific midi note value with the note argument to react to. If you set it to -1 it will trigger on any note. 104 | - If a new hit starts when the old one is still playing, the transision length is defined by lerp_length (length in sample frames). 105 | - `add_debug_sine(name: string, gain: float, angle: float, floww: string);` A super simple synth that plays a pure sine wave. Just for testing and debugging. Doesn't even have attack and decay so it will destort every begin and end of note. 106 | - `add_synth(name: string, gain: float, angle: float, floww: string, square_gain: float, square_z: float, square_adsr_conf: {float}, topflat_gain: float, topflat_z: float, topflat_adsr_conf: {float}, triangle_gain: float, triangle_adsr_conf: {float});` A synth vertex that emits sound given the floww. 107 | - square_gain: gain of the square wave oscilator 108 | - square_z: param going from zero to one, zero meaning completely square wave and one meaning completely sine wave. You can have values inbetween. 109 | - square_adsr_conf: an adsr config for the square oscilator 110 | - topflat_gain: gain of the top flat sine wave oscilator 111 | - topflat_z: param going from zero to one, zero meaning completely top flat sine wave and one meaning completely sine wave. You can have values inbetween. 112 | - topflat_adsr_conf: an adsr config for the square oscilator 113 | - triangle_gain: gain of the triangle wave oscilator 114 | - triangle_adsr_conf: adsr conf for the triangle oscilator 115 | - For a better understanding of the first two oscilators see [graphtoy](https://graphtoy.com/?f1(x,t)=min(sin(x),0)*2+1&v1=false&f2(x,t)=max(sin(x),0)*2-1&v2=false&f3(x,t)=0.4&v3=true&f4(x,t)=(min(sin(x),f3(0))+((1-f3(0))/2))*(2/(1+f3(0)))&v4=false&f5(x,t)=(max(sin(x),-f3(0))-((1-f3(0))/2))*(2/(1+f3(0)))&v5=false&f6(x,t)=clamp(sin(x),%20-f3(0),%20f3(0))%20*%20(1%20/%20f3(0))&v6=true&grid=true&coords=0,0,4.205926793776712) 116 | - `add_lv2fx(name: string, gain: float, angle: float, wetness: float, plugin: string);` Adds a vertex that sums incomming audio and applies a lv2 fx plugin on it. wetness is how much of the new signal is mixed in. With 0.0 the vertex has no effect and with 1.0 the vertex outputs the signal after the plugin is aplied. With 0.5, for example, it is half the original signal and half the processed signal. 117 | - `add_adsr(name: string, gain: float, angle: float, wetness: float, floww: string, use_off: bool, use_max: bool, note: int, adsr_conf: {float});` 118 | This vertex sums the intputs and takes a floww. Based on the flow it applies the adsr envelope on the input signal and outputs it. 119 | - wettness: how much of the processed signal is mixed in 0.0 for none and 1.0 for full 120 | - use_off: whether to listen to the note off event off the floww 121 | - use_max: whether to max (true) or min (true) the primary and ghost note values. Choose max if you have a normal envelope and min if you have an inverted one (ie. one that dips in velocity and has a default value of more than zero). 122 | - note: specific midi note value to trigger on, -1 for all notes 123 | - adsr_conf: the adsr config to apply on the audio 124 | - `add_bandpass(name: string, gain: float, angle: float, wet: float, cut_off_hz_low: float, cut_off_hz_high: float, pass: bool);` 125 | - wettness: how much of the processed signal is mixed in 0.0 for none and 1.0 for full 126 | - cut_off_hz_low: lowpass will let through signal under this hz and will roll off above after it 127 | - cut_off_hz_high: highpass will let through signal above this hz and will roll off under it 128 | - pass: when true it's a pass, when false it's a cut 129 | - `connect(a: string, b: string);` Takes two names of vertices and connects them to eachother. The output of a will be the intput for b. 130 | - 'set_output(out: string);' Takes a name of a vertex and sets this to be the last vertex: the output of this vertex will be the final result. 131 | -------------------------------------------------------------------------------- /examples/neg-adsr-env-example.lua: -------------------------------------------------------------------------------- 1 | -- Our lua file, where we do all the work 2 | set_length(40.0); 3 | set_render_samplerate(48000); 4 | set_render_bitdepth(16); 5 | set_output_file("outp.wav"); 6 | 7 | -- some background sample that loops 8 | load_sample("background", "/home/cody/temp/bg.wav", ""); 9 | load_sample("kick", "/home/cody/doc/samples/drumnbass/kick/kick-v-9.wav", ""); 10 | 11 | load_midi_floww("bassd", "/home/cody/git/music-gen/bassd.midi"); 12 | 13 | add_sample_lerp("kick", 1.0, 0.0, "kick", "bassd", -1, 40); 14 | add_sampleloop("background", 1.0, 0.0, "background"); 15 | dip = 0.3; 16 | adsr = { 1.0, 0.01, dip, 0.2, dip, 0.0, 0.0, 0.05, 1.0 }; 17 | add_adsr("env", 1.0, 0.0, 1.0, "bassd", false, false, -1, adsr); 18 | add_normalize("sum", 1.0, 0.0); 19 | 20 | connect("kick", "sum"); 21 | connect("background", "env"); 22 | connect("env", "sum"); 23 | 24 | set_output("sum"); 25 | -------------------------------------------------------------------------------- /examples/sample-project.lua: -------------------------------------------------------------------------------- 1 | set_length(40.0); 2 | set_render_samplerate(48000); 3 | set_render_bitdepth(16); 4 | set_output_file("outp.wav"); 5 | 6 | load_sample("snare", "/home/cody/doc/samples/drumnbass/snare-1/snare-1-v-9.wav", ""); 7 | load_sample("kick", "/home/cody/doc/samples/drumnbass/kick/kick-v-9.wav", ""); 8 | load_sample("hihat", "/home/cody/doc/samples/drumnbass/hi-hats/closed.wav", ""); 9 | load_sample("ride", "/home/cody/doc/samples/drumnbass/ride/standard.wav", ""); 10 | 11 | load_midi_floww("bassd", "/home/cody/git/music-gen/bassd.midi"); 12 | load_midi_floww("snare", "/home/cody/git/music-gen/snare.midi"); 13 | load_midi_floww("comping", "/home/cody/git/music-gen/comping0.midi"); 14 | load_midi_floww("bass", "/home/cody/git/music-gen/bass.midi"); 15 | load_midi_floww("hihat", "/home/cody/git/music-gen/hihat.midi"); 16 | load_midi_floww("ride", "/home/cody/git/music-gen/ride.midi"); 17 | 18 | load_lv2("reverb", "http://calf.sourceforge.net/plugins/Reverb"); 19 | load_lv2("chorus", "http://calf.sourceforge.net/plugins/MultiChorus"); 20 | load_lv2("compressor", "http://calf.sourceforge.net/plugins/Compressor"); 21 | load_lv2("tape", "http://calf.sourceforge.net/plugins/TapeSimulator"); 22 | 23 | parameter("compressor", "Attack", 40.0); 24 | parameter("compressor", "Release", 100.0); 25 | parameter("compressor", "Knee", 4.0); 26 | parameter("compressor", "Ratio", 2.0); 27 | 28 | load_resource("testtable", "/home/cody/git/sampsyn/table"); 29 | 30 | add_sample_lerp("kick", 2.0, 0.0, "kick", "bassd", -1, 40); 31 | add_sample_lerp("snare", 1.0, 0.0, "snare", "snare", -1, 40); 32 | add_sample_lerp("hihat", 0.8, 50.0, "hihat", "hihat", -1, 40); 33 | add_sample_lerp("ride", 0.8, -50.0, "ride", "ride", -1, 40); 34 | 35 | hit_adsr = { 0.001, 0.02, 0.0, 0.0, 0.0, 0.0 }; 36 | note_adsr = { 0.01, 0.1, 0.8, 5.0, 0.2, 0.5 }; 37 | std_adsr = { 0.01, 1.0, 1.0, 1.0, 1.0, 0.4 }; 38 | add_synth("bass", 0.5, 0.0, "bass", 0.4, 0.3, hit_adsr, 1.0, 0.8, note_adsr, 0.0, {}); 39 | --add_synth("comp", 0.5, 0.0, "comping", 0.5, 0.2, hit_adsr, 1.0, 0.7, note_adsr, 0.0, {}); 40 | add_sampsyn("comp", 0.5, 0.0, "comping", std_adsr, "testtable"); 41 | 42 | add_lv2fx("chorus", 1.0, 0.0, 1.0, "chorus"); 43 | add_lv2fx("reverb", 1.0, 0.0, 0.9, "reverb"); 44 | add_lv2fx("compress", 1.0, 0.0, 1.0, "compressor"); 45 | add_lv2fx("tape", 1.0, 0.0, 1.0, "tape"); 46 | 47 | add_normalize("sum", 1.0, 0.0); 48 | 49 | connect("kick", "compress"); 50 | connect("snare", "compress"); 51 | connect("hihat", "reverb"); 52 | connect("ride", "reverb"); 53 | connect("bass", "chorus"); 54 | connect("comp", "chorus"); 55 | 56 | connect("chorus", "reverb"); 57 | connect("reverb", "compress"); 58 | connect("compress", "tape"); 59 | connect("tape", "sum"); 60 | 61 | set_output("sum"); 62 | -------------------------------------------------------------------------------- /examples/sample-synth-adsr-lv2fx-example.lua: -------------------------------------------------------------------------------- 1 | set_length(40.0); 2 | set_render_samplerate(48000); 3 | set_render_bitdepth(16); 4 | set_output_file("outp.wav"); 5 | 6 | load_sample("snare", "/home/cody/doc/samples/drumnbass/snare-1/snare-1-v-9.wav", ""); 7 | load_sample("kick", "/home/cody/doc/samples/drumnbass/kick/kick-v-9.wav", ""); 8 | 9 | load_midi_floww("bassd", "/home/cody/git/music-gen/bassd.midi"); 10 | load_midi_floww("snare", "/home/cody/git/music-gen/snare.midi"); 11 | load_midi_floww("comping", "/home/cody/git/music-gen/comping0.midi"); 12 | load_lv2("reverb", "http://calf.sourceforge.net/plugins/Reverb"); 13 | load_lv2("chorus", "http://calf.sourceforge.net/plugins/MultiChorus"); 14 | load_lv2("compressor", "http://calf.sourceforge.net/plugins/Compressor"); 15 | load_lv2("tape", "http://calf.sourceforge.net/plugins/TapeSimulator"); 16 | 17 | add_sample_lerp("kick", 1.0, 0.0, "kick", "bassd", -1, 40); 18 | add_sample_lerp("snare", 1.0, 0.0, "snare", "snare", -1, 40); 19 | 20 | hit_adsr = { 0.001, 0.02, 0.0, 0.0, 0.0, 0.0 } 21 | note_adsr = { 0.01, 0.1, 0.8, 5.0, 0.2, 0.5 }; 22 | add_synth("comp", 0.3, 0.0, "comping", 0.5, 0.2, hit_adsr, 1.0, 0.7, note_adsr, 0.0, {}); 23 | add_adsr("env", 1.0, 0.0, 1.0, "snare", false, true, -1, { 0.01, 0.1, 0.8, 0.1, 0.2, 0.01 }); 24 | 25 | add_lv2fx("reverb", 1.0, 0.0, 0.9, "reverb"); 26 | add_lv2fx("chorus", 1.0, 0.0, 1.0, "chorus"); 27 | add_lv2fx("compress", 1.0, 0.0, 1.0, "compressor"); 28 | add_lv2fx("tape", 1.0, 0.0, 1.0, "tape"); 29 | 30 | add_normalize("sum", 1.0, 0.0); 31 | 32 | connect("kick", "sum"); 33 | connect("snare", "env"); 34 | connect("env", "sum"); 35 | connect("comp", "chorus"); 36 | connect("chorus", "reverb"); 37 | connect("reverb", "compress"); 38 | connect("compress", "tape"); 39 | connect("tape", "sum"); 40 | 41 | set_output("sum"); 42 | -------------------------------------------------------------------------------- /examples/stream.lua: -------------------------------------------------------------------------------- 1 | load_sample("snare", "/home/cody/doc/samples/drumnbass/snare-2-damped/snare-2-dampened-v-2.wav", "mix-down"); 2 | load_sample("kick", "/home/cody/doc/samples/drumnbass/kick/kick-v-9.wav", "mix-down"); 3 | load_sample("hihat", "/home/cody/doc/samples/drumnbass/hi-hats/tight.wav", "normalize-seperate"); 4 | load_sample("ride", "/home/cody/doc/samples/drumnbass/ride/standard.wav", "normalize-seperate"); 5 | 6 | load_resource("comp-table", "/home/cody/git/sampsyn/hollowbody.wtable"); 7 | load_resource("bass-table", "/home/cody/git/sampsyn/nylon.wtable"); 8 | 9 | declare_stream("ride"); 10 | declare_stream("hihat"); 11 | declare_stream("kick"); 12 | declare_stream("snare"); 13 | declare_stream("chords"); 14 | declare_stream("bass") 15 | 16 | add_sample_lerp("kick", 1.0, 0.0, "kick", "kick", -1, 40); 17 | add_sample_lerp("snare", 1.0, 0.0, "snare", "snare", -1, 40); 18 | add_sample_lerp("hihat", 3.0, 20.0, "hihat", "hihat", -1, 40); 19 | add_sample_lerp("ride", 1.0, -20.0, "ride", "ride", -1, 40); 20 | 21 | hit_adsr = { 0.001, 0.02, 0.0, 0.0, 0.0, 0.0 }; 22 | note_adsr = { 0.01, 0.1, 0.8, 5.0, 0.2, 0.5 }; 23 | -- add_synth("comping", 0.9, 0.0, "chords", 0.3, 0.0, hit_adsr, 0.0, 0.0, {}, 1.0, note_adsr); 24 | -- name, gain, angle, floww, adsr_conf, resource 25 | add_sampsyn("comping", 0.8, 0.0, "chords", note_adsr, "comp-table"); 26 | 27 | bass_adsr = { 0.01, 2.0, 1.0, 5.0, 0.0, 0.05 }; 28 | add_sampsyn("bass", 2.0, 0.0, "bass", bass_adsr, "bass-table"); 29 | 30 | add_normalize("sum", 0.7, 0.0); 31 | 32 | connect("kick", "sum"); 33 | connect("snare", "sum"); 34 | connect("hihat", "sum"); 35 | connect("ride", "sum"); 36 | connect("comping", "sum"); 37 | connect("bass", "sum"); 38 | 39 | set_output("sum"); 40 | -------------------------------------------------------------------------------- /project.lua: -------------------------------------------------------------------------------- 1 | set_length(40.0); 2 | set_render_samplerate(48000); 3 | set_render_bitdepth(16); 4 | set_output_file("outp.wav"); 5 | 6 | load_sample("snare", "/home/cody/doc/samples/drumnbass/snare-1/snare-1-v-9.wav", ""); 7 | load_sample("kick", "/home/cody/doc/samples/drumnbass/kick/kick-v-9.wav", ""); 8 | load_sample("hihat", "/home/cody/doc/samples/drumnbass/hi-hats/closed.wav", ""); 9 | load_sample("ride", "/home/cody/doc/samples/drumnbass/ride/standard.wav", ""); 10 | 11 | load_midi_floww("bassd", "/home/cody/git/music-gen/bassd.midi"); 12 | load_midi_floww("snare", "/home/cody/git/music-gen/snare.midi"); 13 | load_midi_floww("comping", "/home/cody/git/music-gen/comping0.midi"); 14 | load_midi_floww("bass", "/home/cody/git/music-gen/bass.midi"); 15 | load_midi_floww("hihat", "/home/cody/git/music-gen/hihat.midi"); 16 | load_midi_floww("ride", "/home/cody/git/music-gen/ride.midi"); 17 | 18 | load_lv2("reverb", "http://calf.sourceforge.net/plugins/Reverb"); 19 | load_lv2("chorus", "http://calf.sourceforge.net/plugins/MultiChorus"); 20 | load_lv2("compressor", "http://calf.sourceforge.net/plugins/Compressor"); 21 | load_lv2("tape", "http://calf.sourceforge.net/plugins/TapeSimulator"); 22 | 23 | parameter("compressor", "Attack", 40.0); 24 | parameter("compressor", "Release", 100.0); 25 | parameter("compressor", "Knee", 4.0); 26 | parameter("compressor", "Ratio", 2.0); 27 | 28 | load_resource("testtable", "/home/cody/git/sampsyn/table"); 29 | 30 | add_sample_lerp("kick", 5.0, 0.0, "kick", "bassd", -1, 40); 31 | add_sample_lerp("snare", 0.9, 0.0, "snare", "snare", -1, 40); 32 | add_sample_lerp("hihat", 0.3, 50.0, "hihat", "hihat", -1, 40); 33 | add_sample_lerp("ride", 0.3, -50.0, "ride", "ride", -1, 40); 34 | 35 | hit_adsr = { 0.001, 0.02, 0.0, 0.0, 0.0, 0.0 }; 36 | note_adsr = { 0.01, 0.1, 0.8, 5.0, 0.2, 0.5 }; 37 | std_adsr = { 0.01, 1.0, 1.0, 1.0, 1.0, 0.4 }; 38 | add_synth("bass", 0.35, 0.0, "bass", 0.4, 0.3, hit_adsr, 1.0, 0.8, note_adsr, 0.0, {}); 39 | --add_synth("comp", 0.5, 0.0, "comping", 0.5, 0.2, hit_adsr, 1.0, 0.7, note_adsr, 0.0, {}); 40 | add_sampsyn("comp", 0.2, 0.0, "comping", std_adsr, "testtable"); 41 | 42 | add_lv2fx("chorus", 1.0, 0.0, 1.0, "chorus"); 43 | add_lv2fx("reverb", 1.0, 0.0, 0.9, "reverb"); 44 | add_lv2fx("compress", 1.0, 0.0, 1.0, "compressor"); 45 | add_lv2fx("tape", 1.0, 0.0, 1.0, "tape"); 46 | add_bandpass("band", 1.0, 0.0, 1.0, 1000, 0, true); 47 | add_bandpass("kickband", 1.0, 0.0, 1.0, 0, 50, true) 48 | 49 | add_normalize("sum", 1.0, 0.0); 50 | 51 | connect("kick", "kickband"); 52 | connect("snare", "compress"); 53 | connect("hihat", "reverb"); 54 | connect("ride", "reverb"); 55 | connect("bass", "reverb"); 56 | connect("comp", "chorus"); 57 | 58 | connect("kickband", "compress"); 59 | connect("chorus", "reverb"); 60 | connect("reverb", "compress"); 61 | connect("compress", "tape"); 62 | connect("tape", "band"); 63 | connect("band", "sum"); 64 | 65 | set_output("sum"); 66 | -------------------------------------------------------------------------------- /project.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "Example Project" 3 | 4 | [settings] 5 | # main = "examples/sample-project.lua" 6 | main = "examples/stream.lua" 7 | buffer_length = 1024 8 | project_samplerate = 48000 9 | workflow = "stream" 10 | -------------------------------------------------------------------------------- /src/adsr.rs: -------------------------------------------------------------------------------- 1 | #[derive(Clone, Copy, Default)] 2 | pub struct AdsrConf{ 3 | pub std_vel: f32, 4 | pub attack_sec: f32, 5 | pub attack_vel: f32, 6 | pub decay_sec: f32, 7 | pub decay_vel: f32, 8 | pub sustain_sec: f32, 9 | pub sustain_vel: f32, 10 | pub release_sec: f32, 11 | pub release_vel: f32, 12 | } 13 | 14 | impl AdsrConf{ 15 | pub fn hit_conf( 16 | attack_sec: f32, decay_sec: f32, decay_vel: f32, 17 | sustain_sec: f32, sustain_vel: f32, release_sec: f32 18 | ) -> Self{ 19 | Self{ 20 | std_vel: 0.0, 21 | attack_sec, 22 | attack_vel: 1.0, 23 | decay_sec, 24 | decay_vel, 25 | sustain_sec, 26 | sustain_vel, 27 | release_sec, 28 | release_vel: 0.0, 29 | } 30 | } 31 | 32 | pub fn max_vel(&self) -> f32{ 33 | self.std_vel 34 | .max(self.attack_vel) 35 | .max(self.decay_vel) 36 | .max(self.sustain_vel) 37 | .max(self.release_vel) 38 | } 39 | } 40 | 41 | #[inline] 42 | pub fn lerp(a: f32, b: f32, t: f32) -> f32{ 43 | a + t * (b - a) 44 | } 45 | 46 | fn apply_ads_internal(conf: &AdsrConf, t: f32) -> f32{ 47 | if t <= conf.attack_sec { 48 | lerp(conf.std_vel, conf.attack_vel, t / conf.attack_sec) 49 | } else if t <= conf.attack_sec + conf.decay_sec{ 50 | lerp(conf.attack_vel, conf.decay_vel, (t - conf.attack_sec) / conf.decay_sec) 51 | } else if t <= conf.attack_sec + conf.decay_sec + conf.sustain_sec{ 52 | lerp( 53 | conf.decay_vel, 54 | conf.sustain_vel, 55 | (t - conf.attack_sec - conf.decay_sec) / conf.sustain_sec 56 | ) 57 | } else { 58 | -1000.0 59 | } 60 | } 61 | 62 | pub fn apply_ads(conf: &AdsrConf, t: f32) -> f32{ 63 | let res = apply_ads_internal(conf, t); 64 | if res <= -1.0{ 65 | conf.sustain_vel 66 | } else { 67 | res 68 | } 69 | } 70 | 71 | pub fn apply_r(conf: &AdsrConf, t: f32, old_val: f32) -> f32{ 72 | lerp(old_val, conf.release_vel, (t / conf.release_sec).min(1.0)) 73 | } 74 | 75 | pub fn apply_adsr(conf: &AdsrConf, t: f32) -> f32{ 76 | let res = apply_ads_internal(conf, t); 77 | if res <= -1.0{ 78 | lerp( 79 | conf.sustain_vel, 80 | conf.release_vel, 81 | ((t - conf.attack_sec - conf.decay_sec - conf.sustain_sec) / conf.release_sec).min(1.0) 82 | ) 83 | } else { 84 | res 85 | } 86 | } 87 | 88 | // apply release with release time instead of release value 89 | pub fn apply_r_rt(conf: &AdsrConf, t: f32, rt: f32) -> f32{ 90 | let rv = apply_ads(conf, rt); 91 | apply_r(conf, t, rv) 92 | } 93 | 94 | pub fn build_adsr_conf(arr: &[f32]) -> Option{ 95 | if arr.is_empty(){ 96 | Some(AdsrConf::default()) 97 | } else if arr.len() == 6 { 98 | Some(AdsrConf::hit_conf(arr[0], arr[1], arr[2], arr[3], arr[4], arr[5])) 99 | } else if arr.len() == 9 { 100 | Some(AdsrConf{ 101 | std_vel: arr[0], 102 | attack_sec: arr[1], 103 | attack_vel: arr[2], 104 | decay_sec: arr[3], 105 | decay_vel: arr[4], 106 | sustain_sec: arr[5], 107 | sustain_vel: arr[6], 108 | release_sec: arr[7], 109 | release_vel: arr[8], 110 | }) 111 | } else { 112 | None 113 | } 114 | } 115 | 116 | #[cfg(test)] 117 | mod tests{ 118 | use crate::adsr::*; 119 | 120 | #[test] 121 | fn adsr_0(){ // adsr test 122 | let conf = AdsrConf::hit_conf(1.0, 1.0, 0.5, 1.0, 0.25, 1.0); 123 | assert!(apply_adsr(&conf, 0.0).abs() < 0.001); 124 | assert!((0.5 - apply_adsr(&conf, 0.5)).abs() < 0.001); 125 | assert!((1.0 - apply_adsr(&conf, 1.0)).abs() < 0.001); 126 | assert!((0.75 - apply_adsr(&conf, 1.5)).abs() < 0.001); 127 | assert!((0.5 - apply_adsr(&conf, 2.0)).abs() < 0.001); 128 | assert!((0.375 - apply_adsr(&conf, 2.5)).abs() < 0.001); 129 | assert!((0.25 - apply_adsr(&conf, 3.0)).abs() < 0.001); 130 | assert!((0.125 - apply_adsr(&conf, 3.5)).abs() < 0.001); 131 | assert!((0.0 - apply_adsr(&conf, 4.0)).abs() < 0.001); 132 | assert!((0.0 - apply_adsr(&conf, 8.0)).abs() < 0.001); 133 | } 134 | 135 | #[test] 136 | fn adsr_1(){ // ads+r test, going into release mode after sustain window 137 | let conf = AdsrConf::hit_conf(1.0, 1.0, 0.5, 1.0, 0.25, 1.0); 138 | assert!(apply_adsr(&conf, 0.0).abs() < 0.001); 139 | assert!((0.5 - apply_ads(&conf, 0.5)).abs() < 0.001); 140 | assert!((1.0 - apply_ads(&conf, 1.0)).abs() < 0.001); 141 | assert!((0.75 - apply_ads(&conf, 1.5)).abs() < 0.001); 142 | assert!((0.5 - apply_ads(&conf, 2.0)).abs() < 0.001); 143 | assert!((0.375 - apply_ads(&conf, 2.5)).abs() < 0.001); 144 | assert!((0.25 - apply_ads(&conf, 3.0)).abs() < 0.001); 145 | assert!((0.25 - apply_ads(&conf, 7.0)).abs() < 0.001); 146 | assert!((0.25 - apply_r(&conf, 0.0, 0.25)).abs() < 0.001); 147 | assert!((0.125 - apply_r(&conf, 0.5, 0.25)).abs() < 0.001); 148 | assert!((0.0 - apply_r(&conf, 1.0, 0.25)).abs() < 0.001); 149 | assert!((0.0 - apply_r(&conf, 9.0, 0.25)).abs() < 0.001); 150 | } 151 | 152 | #[test] 153 | fn adsr_2(){ // ads+r test, going into release mode in sustain window 154 | let conf = AdsrConf::hit_conf(1.0, 1.0, 0.5, 2.0, 0.25, 1.0); 155 | assert!(apply_adsr(&conf, 0.0).abs() < 0.001); 156 | assert!((0.5 - apply_ads(&conf, 0.5)).abs() < 0.001); 157 | assert!((1.0 - apply_ads(&conf, 1.0)).abs() < 0.001); 158 | assert!((0.75 - apply_ads(&conf, 1.5)).abs() < 0.001); 159 | assert!((0.5 - apply_ads(&conf, 2.0)).abs() < 0.001); 160 | assert!((0.375 - apply_ads(&conf, 3.0)).abs() < 0.001); 161 | assert!((0.375 - apply_r(&conf, 0.0, 0.375)).abs() < 0.001); 162 | assert!((0.1875 - apply_r(&conf, 0.5, 0.375)).abs() < 0.001); 163 | assert!((0.0 - apply_r(&conf, 1.0, 0.375)).abs() < 0.001); 164 | assert!((0.0 - apply_r(&conf, 9.0, 0.375)).abs() < 0.001); 165 | } 166 | 167 | #[test] 168 | fn adsr_3(){ // ads+r test, apply_r_rt 169 | let conf = AdsrConf::hit_conf(1.0, 1.0, 0.5, 2.0, 0.25, 1.0); 170 | assert!(apply_adsr(&conf, 0.0).abs() < 0.001); 171 | assert!((0.5 - apply_ads(&conf, 0.5)).abs() < 0.001); 172 | assert!((1.0 - apply_ads(&conf, 1.0)).abs() < 0.001); 173 | assert!((0.75 - apply_ads(&conf, 1.5)).abs() < 0.001); 174 | assert!((0.5 - apply_ads(&conf, 2.0)).abs() < 0.001); 175 | assert!((0.375 - apply_ads(&conf, 3.0)).abs() < 0.001); 176 | assert!((0.375 - apply_r_rt(&conf, 0.0, 3.0)).abs() < 0.001); 177 | assert!((0.1875 - apply_r_rt(&conf, 0.5, 3.0)).abs() < 0.001); 178 | assert!((0.0 - apply_r_rt(&conf, 1.0, 3.0)).abs() < 0.001); 179 | assert!((0.0 - apply_r_rt(&conf, 9.0, 3.0)).abs() < 0.001); 180 | } 181 | 182 | #[test] 183 | fn adsr_4(){ // adsr test that dips instead of peaks 184 | let conf = AdsrConf{ 185 | std_vel: 1.0, 186 | attack_sec: 1.0, 187 | attack_vel: 0.0, 188 | decay_sec: 0.5, 189 | decay_vel: 0.0, 190 | sustain_sec: 0.5, 191 | sustain_vel: 0.0, 192 | release_sec: 1.0, 193 | release_vel: 1.0, 194 | }; 195 | assert!((1.0 - apply_adsr(&conf, 0.0)).abs() < 0.001); 196 | assert!((0.5 - apply_adsr(&conf, 0.5)).abs() < 0.001); 197 | assert!((0.0 - apply_adsr(&conf, 1.0)).abs() < 0.001); 198 | assert!((0.0 - apply_adsr(&conf, 1.5)).abs() < 0.001); 199 | assert!((0.0 - apply_adsr(&conf, 2.0)).abs() < 0.001); 200 | assert!((0.5 - apply_adsr(&conf, 2.5)).abs() < 0.001); 201 | assert!((1.0 - apply_adsr(&conf, 3.0)).abs() < 0.001); 202 | assert!((1.0 - apply_adsr(&conf, 4.0)).abs() < 0.001); 203 | assert!((1.0 - apply_adsr(&conf, 8.0)).abs() < 0.001); 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /src/bufferbank.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::{ HashMap, HashSet }, 3 | io::prelude::*, 4 | fs::File, 5 | }; 6 | 7 | use zen_colour::*; 8 | 9 | pub type Buffer = Vec; 10 | 11 | pub struct BufferBank{ 12 | buffers: Vec, 13 | names: HashMap, 14 | marked: HashSet, 15 | } 16 | 17 | impl BufferBank{ 18 | pub fn new() -> Self{ 19 | Self{ 20 | buffers: Vec::new(), 21 | names: HashMap::new(), 22 | marked: HashSet::new(), 23 | } 24 | } 25 | 26 | pub fn add(&mut self, name: String, file_path: &str) -> Result<(), String>{ 27 | if self.names.contains_key(&name) { 28 | return Err(format!( 29 | "{r}TermDaw: BufferBank: there is already a blob with name {b}\"{n}\"{r} present.", 30 | r = RED, b = BLUE, n = name 31 | )); 32 | } 33 | 34 | let mut buffer = Vec::new(); 35 | let mut file = if let Ok(file) = File::open(file_path) { file } 36 | else { 37 | return Err(format!( 38 | "{r}TermDaw: BufferBank: could open read file {b}\"{f}\"{r}.", 39 | r = RED, b = BLUE, f = file_path 40 | )); 41 | }; 42 | if file.read_to_end(&mut buffer).is_err() { 43 | return Err(format!( 44 | "{r}TermDaw: BufferBank: could not read file {b}\"{f}\"{r}.", 45 | r = RED, b = BLUE, f = file_path 46 | )); 47 | } 48 | 49 | self.buffers.push(buffer); 50 | self.names.insert(name, self.buffers.len() - 1); 51 | Ok(()) 52 | } 53 | 54 | pub fn mark_dead(&mut self, name: &str){ 55 | if let Some(index) = self.names.get(name){ 56 | self.marked.insert(*index); 57 | } 58 | } 59 | 60 | pub fn refresh(&mut self){ 61 | if self.marked.is_empty() { return; } 62 | let mut new_map = HashMap::new(); 63 | let mut new_vec = Vec::new(); 64 | let names = std::mem::take(&mut self.names); 65 | for (name, index) in names{ 66 | if self.marked.contains(&index) { continue; } 67 | let buffer = std::mem::take(&mut self.buffers[index]); 68 | new_vec.push(buffer); 69 | new_map.insert(name, new_vec.len() - 1); 70 | } 71 | self.names = new_map; 72 | self.buffers = new_vec; 73 | self.marked.clear(); 74 | } 75 | 76 | pub fn get_index(&self, name: &str) -> Option{ 77 | self.names.get(name).copied() 78 | } 79 | 80 | pub fn get_buffer(&self, index: usize) -> &Buffer{ 81 | &self.buffers[index] 82 | } 83 | } 84 | 85 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fs::File, 3 | io::Read, 4 | path::Path, 5 | }; 6 | 7 | use serde::Deserialize; 8 | 9 | impl Config{ 10 | pub fn read(path: &Path) -> Self{ 11 | let mut file = File::open(path).unwrap(); 12 | let mut contents = String::new(); 13 | file.read_to_string(&mut contents).unwrap(); 14 | let config: Config = toml::from_str(&contents).unwrap(); 15 | config 16 | } 17 | } 18 | 19 | #[derive(Deserialize, Clone)] 20 | pub struct Config{ 21 | pub project: Project, 22 | pub settings: Settings, 23 | } 24 | 25 | #[derive(Deserialize, Clone)] 26 | pub struct Project{ 27 | name: Option, 28 | } 29 | 30 | impl Project{ 31 | pub fn name(&self) -> String{ 32 | self.name.clone().unwrap_or_else(|| String::from("unnamed")) 33 | } 34 | } 35 | 36 | #[derive(Clone,Copy,PartialEq,Eq)] 37 | pub enum WorkFlow{ Manual, Stream } 38 | 39 | 40 | impl std::fmt::Display for WorkFlow { 41 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 42 | write!(f, "{}", match self{ 43 | WorkFlow::Manual => "manual", 44 | WorkFlow::Stream => "stream", 45 | }) 46 | } 47 | } 48 | 49 | #[derive(Deserialize, Clone)] 50 | pub struct Settings{ 51 | pub main: String, 52 | buffer_length: Option, 53 | project_samplerate: Option, 54 | workflow: Option, 55 | } 56 | 57 | impl Settings{ 58 | pub fn buffer_length(&self) -> usize{ 59 | self.buffer_length.unwrap_or(1024) 60 | } 61 | 62 | pub fn project_samplerate(&self) -> usize{ 63 | self.project_samplerate.unwrap_or(44100) 64 | } 65 | 66 | pub fn workflow(&self) -> WorkFlow{ 67 | if let Some(string) = &self.workflow{ 68 | match string.as_ref() { 69 | "stream" => WorkFlow::Stream, 70 | _ => WorkFlow::Manual, 71 | } 72 | } else { 73 | WorkFlow::Manual 74 | } 75 | } 76 | } 77 | 78 | -------------------------------------------------------------------------------- /src/extensions.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | sample::{ Sample, SampleBank }, 3 | floww::FlowwBank, 4 | adsr::*, 5 | synth::*, 6 | graph::GenArgs, 7 | lv2::Lv2Host, 8 | }; 9 | 10 | use core::f32::consts::PI; 11 | use std::collections::VecDeque; 12 | 13 | use sampsyn::*; 14 | 15 | pub enum VertexExt{ 16 | Sum, 17 | Normalize{ 18 | max: f32, 19 | scan_max: f32, 20 | }, 21 | SampleLoop{ 22 | sample_index: usize, 23 | t: usize, 24 | }, 25 | SampleMulti{ 26 | sample_index: usize, 27 | floww_index: usize, 28 | note: Option, 29 | ts: VecDeque<(i64, f32)>, 30 | }, 31 | SampleLerp{ 32 | sample_index: usize, 33 | floww_index: usize, 34 | note: Option, 35 | lerp_len: usize, 36 | countdown: usize, 37 | primary: (i64, f32), 38 | ghost: (i64, f32), 39 | }, 40 | DebugSine{ 41 | floww_index: usize, 42 | notes: Vec<(f32, f32)>, 43 | }, 44 | Synth{ 45 | floww_index: usize, 46 | square_conf: OscConf, 47 | topflat_conf: OscConf, 48 | triangle_conf: OscConf, 49 | notes: Vec<(f32, f32, f32, f32)>, 50 | }, 51 | SampSyn{ 52 | floww_index: usize, 53 | adsr: AdsrConf, 54 | wave_table: WaveTable, 55 | notes: Vec<(f32, f32, f32, f32, WaveTableState)>, 56 | }, 57 | #[cfg(feature = "lv2")] 58 | Lv2fx{ 59 | index: usize, 60 | }, 61 | Adsr{ 62 | use_off: bool, 63 | use_max: bool, 64 | conf: AdsrConf, 65 | floww_index: usize, 66 | note: Option, 67 | primary: (f32, f32, f32), 68 | ghost: (f32, f32, f32), 69 | }, 70 | BandPass{ 71 | lgamma: f32, 72 | hgamma: f32, 73 | lprevl: f32, 74 | lprevr: f32, 75 | hprevl: f32, 76 | hprevr: f32, 77 | first: bool, 78 | pass: bool, 79 | } 80 | } 81 | 82 | impl VertexExt{ 83 | pub fn sum() -> Self{ 84 | Self::Sum 85 | } 86 | 87 | pub fn normalize() -> Self{ 88 | Self::Normalize{ 89 | max: 0.0, // values on scan 90 | scan_max: 0.0, 91 | } 92 | } 93 | 94 | pub fn sample_loop(sample_index: usize) -> Self{ 95 | Self::SampleLoop{ 96 | sample_index, 97 | t: 0, 98 | } 99 | } 100 | 101 | pub fn sample_multi(sample_index: usize, floww_index: usize, note: Option) -> Self{ 102 | Self::SampleMulti{ 103 | sample_index, 104 | floww_index, 105 | ts: VecDeque::new(), 106 | note, 107 | } 108 | } 109 | 110 | pub fn sample_lerp( 111 | sample_index: usize, floww_index: usize, note: Option, lerp_len: usize 112 | ) -> Self{ 113 | Self::SampleLerp{ 114 | sample_index, 115 | floww_index, 116 | note, 117 | lerp_len, 118 | countdown: 0, 119 | primary: (0, 0.0), 120 | ghost: (0, 0.0), 121 | } 122 | } 123 | 124 | pub fn debug_sine(floww_index: usize) -> Self{ 125 | Self::DebugSine{ 126 | floww_index, 127 | notes: Vec::new(), 128 | } 129 | } 130 | 131 | pub fn synth( 132 | floww_index: usize, square_conf: OscConf, topflat_conf: OscConf, triangle_conf: OscConf 133 | ) -> Self{ 134 | Self::Synth{ 135 | floww_index, 136 | notes: Vec::new(), 137 | square_conf, 138 | topflat_conf, 139 | triangle_conf, 140 | } 141 | } 142 | 143 | pub fn sampsyn(floww_index: usize, adsr: AdsrConf, wave_table: WaveTable) -> Self{ 144 | Self::SampSyn{ 145 | floww_index, 146 | adsr, 147 | wave_table, 148 | notes: Vec::new(), 149 | } 150 | } 151 | 152 | #[cfg(feature = "lv2")] 153 | pub fn lv2fx(plugin_index: usize) -> Self{ 154 | Self::Lv2fx{ 155 | index: plugin_index, 156 | } 157 | } 158 | 159 | pub fn adsr( 160 | use_off: bool, use_max: bool, conf: AdsrConf, note: Option, floww_index: usize 161 | ) -> Self{ 162 | Self::Adsr{ 163 | use_off, 164 | use_max, 165 | conf, 166 | note, 167 | floww_index, 168 | primary: (0.0, 0.0, 0.0), 169 | ghost: (0.0, 0.0, 0.0), 170 | } 171 | } 172 | 173 | pub fn band_pass( 174 | cut_off_hz_low: f32, cut_off_hz_hig: f32, pass: bool, sampling_hz: usize 175 | ) -> Self{ 176 | let lco = cut_off_hz_low.min(20000.0).max(0.0); 177 | let hco = cut_off_hz_hig.min(20000.0).max(0.0); 178 | let lgamma = 1.0 - std::f32::consts::E.powf( 179 | -2.0 * std::f32::consts::PI * lco / sampling_hz as f32 180 | ); 181 | let hgamma = 1.0 - std::f32::consts::E.powf( 182 | -2.0 * std::f32::consts::PI * hco / sampling_hz as f32 183 | ); 184 | Self::BandPass{ 185 | lgamma, 186 | hgamma, 187 | lprevl: 0.0, 188 | lprevr: 0.0, 189 | hprevl: 0.0, 190 | hprevr: 0.0, 191 | first: true, 192 | pass, 193 | } 194 | } 195 | 196 | pub fn set_time(&mut self, time: usize){ 197 | match self{ 198 | Self::SampleLoop { t, .. } => { *t = time; }, 199 | Self::DebugSine { notes, .. } => { notes.clear(); }, 200 | Self::Synth { notes, .. } => { notes.clear(); }, 201 | Self::BandPass { first, .. } => { *first = true; }, 202 | _ => { }, 203 | } 204 | } 205 | 206 | #[allow(clippy::too_many_arguments)] 207 | pub fn generate( 208 | &mut self, ga: GenArgs, sb: &SampleBank, fb: &mut FlowwBank, _host: &mut Lv2Host, 209 | gain: f32, angle: f32, wet: f32, buf: &mut Sample, res: Vec<&Sample> 210 | ){ 211 | let (t, sr, len, is_scan) = ga; 212 | if self.has_input(){ 213 | sum_inputs(buf, len, res); 214 | } 215 | match self{ 216 | Self::Sum => { }, 217 | Self::Normalize { max, scan_max } => { 218 | normalize_gen(buf, len, max, scan_max, is_scan); 219 | }, 220 | Self::SampleLoop { t, sample_index } => { 221 | sample_loop_gen(buf, sb, len, t, *sample_index); 222 | }, 223 | Self::SampleMulti { ts, sample_index, floww_index, note } => { 224 | sample_multi_gen(buf, sb, fb, len, ts, *sample_index, *floww_index, *note); 225 | }, 226 | Self::SampleLerp { 227 | sample_index, floww_index, note, countdown, lerp_len, primary, ghost 228 | } => { 229 | sample_lerp_gen( 230 | buf, sb, fb, len, *sample_index, *floww_index, *note, *lerp_len, 231 | countdown, primary, ghost 232 | ); 233 | }, 234 | Self::DebugSine { floww_index, notes } => { 235 | debug_sine_gen(buf, fb, len, *floww_index, notes, t, sr); 236 | }, 237 | Self::Synth { floww_index, notes, square_conf, topflat_conf, triangle_conf } => { 238 | synth_gen( 239 | buf, fb, len, *floww_index, notes, square_conf, topflat_conf, triangle_conf, 240 | t, sr 241 | ); 242 | }, 243 | Self::SampSyn { floww_index, notes, adsr, wave_table } => { 244 | sampsyn_gen(buf, fb, len, *floww_index, notes, adsr, wave_table, sr); 245 | }, 246 | #[cfg(feature = "lv2")] 247 | Self::Lv2fx { index } => { 248 | lv2fx_gen(buf, len, wet, *index, _host); 249 | }, 250 | Self::Adsr { use_off, use_max, conf, note, floww_index, primary, ghost } => { 251 | adsr_gen( 252 | buf, len, fb, wet, *use_off, *use_max, *floww_index, sr, conf, *note, 253 | primary, ghost 254 | ); 255 | }, 256 | Self::BandPass { lprevl, lprevr, hprevl, hprevr, lgamma, hgamma, first, pass } => { 257 | band_pass_gen( 258 | buf, len, wet, first, *pass, *lgamma, *hgamma, lprevl, lprevr, hprevl, hprevr 259 | ); 260 | } 261 | } 262 | buf.apply_angle(angle, len); 263 | buf.apply_gain(gain, len); 264 | } 265 | 266 | pub fn has_input(&self) -> bool{ 267 | match self{ 268 | Self::Sum => true, 269 | Self::Normalize { .. } => true, 270 | Self::SampleLoop { .. } => false, 271 | Self::SampleMulti { .. } => false, 272 | Self::SampleLerp { .. } => false, 273 | Self::DebugSine { .. } => false, 274 | Self::Synth { .. } => false, 275 | Self::SampSyn { .. } => false, 276 | #[cfg(feature = "lv2")] 277 | Self::Lv2fx { .. } => true, 278 | Self::Adsr { .. } => true, 279 | Self::BandPass { .. } => true, 280 | } 281 | } 282 | 283 | pub fn reset_scan_normalization(&mut self){ 284 | if let Self::Normalize { scan_max, .. } = self{ 285 | *scan_max = 0.0; 286 | } 287 | } 288 | 289 | pub fn apply_scan_normalization(&mut self){ 290 | if let Self::Normalize { scan_max, max } = self{ 291 | *max = *scan_max; 292 | } 293 | } 294 | 295 | pub fn reset_normalization(&mut self){ 296 | if let Self::Normalize{ max, .. } = self{ 297 | *max = 0.000001; 298 | } 299 | } 300 | 301 | pub fn get_normalization_value(&self) -> f32{ 302 | if let Self::Normalize{ max, .. } = self{ 303 | *max 304 | } else { 305 | -1.0 306 | } 307 | } 308 | } 309 | 310 | fn sum_inputs(buf: &mut Sample, len: usize, res: Vec<&Sample>){ 311 | buf.zero(); 312 | for r in res{ 313 | let l = r.len().min(len); 314 | for i in 0..l{ 315 | buf.l[i] += r.l[i]; 316 | buf.r[i] += r.r[i]; 317 | } 318 | } 319 | } 320 | 321 | fn normalize_gen(buf: &mut Sample, len: usize, max: &mut f32, scan_max: &mut f32, is_scan: bool){ 322 | let buf_max = buf.scan_max(len); 323 | if is_scan{ 324 | *scan_max = buf_max.max(*scan_max); 325 | } else { 326 | *max = buf_max.max(*max); 327 | } 328 | buf.scale(len, 1.0 / *max); 329 | } 330 | 331 | fn sample_loop_gen( 332 | buf: &mut Sample, sb: &SampleBank, len: usize, t: &mut usize, sample_index: usize 333 | ){ 334 | let sample = sb.get_sample(sample_index); 335 | let l = sample.len(); 336 | for i in 0..len{ 337 | buf.l[i] = sample.l[(*t + i) % l]; 338 | buf.r[i] = sample.r[(*t + i) % l]; 339 | } 340 | *t += len; 341 | } 342 | 343 | #[allow(clippy::too_many_arguments)] 344 | fn sample_multi_gen( 345 | buf: &mut Sample, sb: &SampleBank, fb: &mut FlowwBank, len: usize, 346 | ts: &mut VecDeque<(i64, f32)>, sample_index: usize, floww_index: usize, 347 | target_note: Option 348 | ){ 349 | let sample = sb.get_sample(sample_index); 350 | fb.start_block(floww_index); 351 | for i in 0..len{ 352 | if let Some((note, v)) = fb.get_block_drum(floww_index, i){ 353 | let ok = if let Some(n) = target_note{ 354 | (note - n as f32).abs() < 0.01 355 | } 356 | else { true }; 357 | if ok{ 358 | // line up with i so that (t + i) = (-i + i) = 0 is the first frame copied 359 | ts.push_back((-(i as i64), v)); 360 | } 361 | } 362 | buf.l[i] = 0.0; 363 | buf.r[i] = 0.0; 364 | let mut pops = 0; 365 | for (t, vel) in ts.iter(){ 366 | let pos = (*t + i as i64).max(0) as usize; 367 | if pos >= sample.len() { 368 | pops += 1; 369 | } else { 370 | buf.l[i] += sample.l[pos] * *vel; 371 | buf.r[i] += sample.r[pos] * *vel; 372 | } 373 | } 374 | for _ in 0..pops{ 375 | ts.pop_front(); 376 | } 377 | } 378 | for (t, _) in ts{ 379 | *t += len as i64; 380 | } 381 | } 382 | 383 | #[allow(clippy::too_many_arguments)] 384 | fn sample_lerp_gen( 385 | buf: &mut Sample, sb: &SampleBank, fb: &mut FlowwBank, len: usize, sample_index: usize, 386 | floww_index: usize, target_note: Option, lerp_len: usize, countdown: &mut usize, 387 | primary: &mut (i64, f32), ghost: &mut (i64, f32) 388 | ){ 389 | let sample = sb.get_sample(sample_index); 390 | fb.start_block(floww_index); 391 | for i in 0..len{ 392 | if let Some((note, v)) = fb.get_block_drum(floww_index, i){ 393 | let ok = if let Some(n) = target_note{ 394 | (note - n as f32).abs() < 0.01 395 | } 396 | else { true }; 397 | if ok{ 398 | *ghost = *primary; 399 | // line up with i so that (t + i) = (-i + i) = 0 is the first frame copied 400 | *primary = (-(i as i64), v); 401 | *countdown = lerp_len; 402 | } 403 | } 404 | let primary_pos = ((primary.0 + i as i64).max(0) as usize).min(sample.len() - 1); 405 | let mut l = sample.l[primary_pos] * primary.1; 406 | let mut r = sample.r[primary_pos] * primary.1; 407 | if *countdown > 0{ 408 | *countdown -= 1; 409 | let t = *countdown as f32 / lerp_len as f32; 410 | let ghost_pos = ((ghost.0 + i as i64).max(0) as usize).min(sample.len() - 1); 411 | let gl = sample.l[ghost_pos] * ghost.1; 412 | let gr = sample.r[ghost_pos] * ghost.1; 413 | l = gl * t + l * (1.0 - t); 414 | r = gr * t + r * (1.0 - t); 415 | } 416 | buf.l[i] = l; 417 | buf.r[i] = r; 418 | } 419 | primary.0 += len as i64; 420 | ghost.0 += len as i64; 421 | } 422 | 423 | fn debug_sine_gen( 424 | buf: &mut Sample, fb: &mut FlowwBank, len: usize, floww_index: usize, 425 | notes: &mut Vec<(f32, f32)>, t: usize, sr: usize 426 | ){ 427 | fb.start_block(floww_index); 428 | for i in 0..len{ 429 | for (on, note, vel) in fb.get_block_simple(floww_index, i){ 430 | if on{ 431 | let mut has = false; 432 | for (n, v) in notes.iter_mut(){ 433 | if (*n - note).abs() < 0.001{ 434 | *v = vel; 435 | has = true; 436 | break; 437 | } 438 | } 439 | if !has { 440 | notes.push((note, vel)); 441 | } 442 | } else { 443 | notes.retain(|x| (x.0 - note).abs() > 0.001); 444 | } 445 | } 446 | 447 | buf.l[i] = 0.0; 448 | buf.r[i] = 0.0; 449 | for (note, vel) in notes.iter(){ 450 | let time = (t + i) as f32 / sr as f32; 451 | let hz = 440.0 * (2.0f32).powf((note - 69.0) / 12.0); 452 | let s = (time * hz * 2.0 * PI).sin() * vel; 453 | buf.l[i] += s; 454 | buf.r[i] += s; 455 | } 456 | } 457 | } 458 | 459 | #[allow(clippy::too_many_arguments)] 460 | fn synth_gen( 461 | buf: &mut Sample, fb: &mut FlowwBank, len: usize, floww_index: usize, 462 | notes: &mut Vec<(f32, f32, f32, f32)>, square: &OscConf, topflat: &OscConf, triangle: &OscConf, 463 | t: usize, sr: usize 464 | ){ 465 | let osc_amp_multiplier = 1.0 / ( 466 | square.volume * square.adsr.max_vel() + 467 | topflat.volume * topflat.adsr.max_vel() + 468 | triangle.volume * triangle.adsr.max_vel()); 469 | let mut release_sec = 0.0; 470 | if square.volume > 0.0 { 471 | release_sec = square.adsr.release_sec; 472 | } 473 | if topflat.volume > 0.0 { 474 | release_sec = release_sec.max(topflat.adsr.release_sec); 475 | } 476 | if triangle.volume > 0.0 { 477 | release_sec = release_sec.max(triangle.adsr.release_sec); 478 | } 479 | fb.start_block(floww_index); 480 | for i in 0..len{ 481 | for (on, note, vel) in fb.get_block_simple(floww_index, i){ 482 | if on{ 483 | notes.push((note, vel, -(i as f32 / sr as f32), 0.0)); 484 | } else { 485 | notes.retain(|x| (x.0 - note).abs() > 0.001 || x.3 == 0.0); 486 | for (n, _, env_t, rel_t) in notes.iter_mut(){ 487 | if (*n - note).abs() > 0.001 { continue; } 488 | if *rel_t == 0.0{ 489 | *rel_t = *env_t + (i as f32 / sr as f32); 490 | *env_t = -(i as f32 / sr as f32); 491 | } else { 492 | panic!("Synth: impossible release stage note"); 493 | } 494 | } 495 | } 496 | } 497 | 498 | buf.l[i] = 0.0; 499 | buf.r[i] = 0.0; 500 | for (note, vel, env_t, rel_t) in notes.iter(){ 501 | let time = (t + i) as f32 / sr as f32; 502 | let env_time = env_t + (i as f32 / sr as f32); 503 | let hz = 440.0 * (2.0f32).powf((note - 69.0) / 12.0); 504 | 505 | let env_vel = |adsr_conf| if *rel_t == 0.0 { apply_ads(adsr_conf, env_time) } 506 | else { apply_r_rt(adsr_conf, env_time, *rel_t) }; 507 | 508 | let mut s = 0.0; 509 | if square.volume > 0.0 { 510 | s += square_sine_sample(time, hz, square.param) * vel * env_vel(&square.adsr) 511 | * square.volume; 512 | } 513 | if topflat.volume > 0.0 { 514 | s += topflat_sine_sample(time, hz, topflat.param) * vel * env_vel(&topflat.adsr) 515 | * topflat.volume; 516 | } 517 | if triangle.volume > 0.0 { 518 | s += triangle_sample(time, hz) * vel * env_vel(&triangle.adsr) * triangle.volume; 519 | } 520 | s *= osc_amp_multiplier; 521 | buf.l[i] += s; 522 | buf.r[i] += s; 523 | } 524 | } 525 | for (_, _, env_t, _) in notes.iter_mut(){ 526 | *env_t += len as f32 / sr as f32; 527 | } 528 | notes.retain(|x| x.3 == 0.0 || x.2 <= release_sec); 529 | } 530 | 531 | #[allow(clippy::too_many_arguments)] 532 | fn sampsyn_gen( 533 | buf: &mut Sample, fb: &mut FlowwBank, len: usize, floww_index: usize, 534 | notes: &mut Vec<(f32, f32, f32, f32, WaveTableState)>, adsr: &AdsrConf, wave_table: &WaveTable, 535 | sr: usize 536 | ){ 537 | let amp_multiplier = 1.0 / adsr.max_vel(); 538 | fb.start_block(floww_index); 539 | for i in 0..len{ 540 | for (on, note, vel) in fb.get_block_simple(floww_index, i){ 541 | if on{ 542 | let init_state = initial_state(wave_table, 0.0); 543 | notes.push((note, vel, -(i as f32 / sr as f32), 0.0, init_state)); 544 | } else { 545 | notes.retain(|x| (x.0 - note).abs() > 0.001 || x.3 == 0.0); 546 | for (n, _, env_t, rel_t, _) in notes.iter_mut(){ 547 | if (*n - note).abs() > 0.001 { continue; } 548 | if *rel_t == 0.0{ 549 | *rel_t = *env_t + (i as f32 / sr as f32); 550 | *env_t = -(i as f32 / sr as f32); 551 | } else { 552 | panic!("Synth: impossible release stage note"); 553 | } 554 | } 555 | } 556 | } 557 | 558 | buf.l[i] = 0.0; 559 | buf.r[i] = 0.0; 560 | for (note, vel, env_t, rel_t, state) in notes.iter_mut(){ 561 | let env_time = *env_t + (i as f32 / sr as f32); 562 | let hz = 440.0 * (2.0f32).powf((*note - 69.0) / 12.0); 563 | 564 | let env_vel = |adsr_conf| if *rel_t == 0.0 { apply_ads(adsr_conf, env_time) } 565 | else { apply_r_rt(adsr_conf, env_time, *rel_t) }; 566 | 567 | let mut s = 0.0; 568 | let vel = *vel * env_vel(adsr) * amp_multiplier; 569 | s += wavetable_act_state(wave_table, state, hz, env_time + *rel_t, sr as f32) * vel; 570 | buf.l[i] += s; 571 | buf.r[i] += s; 572 | } 573 | } 574 | for (_, _, env_t, _, _) in notes.iter_mut(){ 575 | *env_t += len as f32 / sr as f32; 576 | } 577 | notes.retain(|x| x.3 == 0.0 || x.2 <= adsr.release_sec); 578 | } 579 | 580 | #[cfg(feature = "lv2")] 581 | fn lv2fx_gen(buf: &mut Sample, len: usize, wet: f32, index: usize, host: &mut Lv2Host){ 582 | if wet < 0.0001 { return; } 583 | for i in 0..len{ 584 | let ll = buf.l[i]; 585 | let rr = buf.r[i]; 586 | let (l, r) = host.apply(index, [0, 0, 0], (ll, rr)); 587 | buf.l[i] = lerp(ll, l, wet); 588 | buf.r[i] = lerp(rr, r, wet); 589 | } 590 | } 591 | 592 | #[allow(clippy::too_many_arguments)] 593 | fn adsr_gen( 594 | buf: &mut Sample, len: usize, fb: &mut FlowwBank, wet: f32, use_off: bool, use_max: bool, 595 | floww_index: usize, sr: usize, conf: &AdsrConf, note: Option, 596 | primary: &mut (f32, f32, f32), ghost: &mut (f32, f32, f32) 597 | ){ 598 | if wet < 0.0001 { return; } 599 | let maxmul = if use_max { 1.0 } else { 0.0 }; 600 | let minmul = 1.0 - maxmul; 601 | fb.start_block(floww_index); 602 | if use_off{ 603 | for i in 0..len{ 604 | let offset = i as f32 / sr as f32; 605 | for (on, n, v) in fb.get_block_simple(floww_index, i){ 606 | if let Some(target) = note{ 607 | if (target as f32 - n).abs() > 0.01 { continue; } 608 | } 609 | if on{ 610 | *ghost = *primary; 611 | *primary = (-(i as f32 / sr as f32), v, 0.0); 612 | } else if ghost.2 == 0.0 { 613 | ghost.0 = -(i as f32 / sr as f32); 614 | ghost.2 = apply_ads(conf, ghost.0 + offset) * ghost.1; 615 | } else { 616 | primary.0 = -(i as f32 / sr as f32); 617 | primary.2 = apply_ads(conf, primary.0 + offset) * primary.1; 618 | } 619 | } 620 | let pvel = if primary.2 == 0.0 { apply_ads(conf, primary.0 + offset) * primary.1 } 621 | else { apply_r(conf, primary.0 + offset, primary.2) * primary.1 }; 622 | let gvel = if ghost.2 == 0.0 { apply_ads(conf, ghost.0 + offset) * ghost.1 } 623 | else { apply_r(conf, ghost.0 + offset, ghost.2) * ghost.1 }; 624 | let adsr_vel = pvel.max(gvel) * maxmul + pvel.min(gvel) * minmul; 625 | let vel = lerp(1.0, adsr_vel, wet); 626 | 627 | buf.l[i] *= vel; 628 | buf.r[i] *= vel; 629 | } 630 | } else { 631 | for i in 0..len{ 632 | if let Some((n, v)) = fb.get_block_drum(floww_index, i){ 633 | if let Some(target) = note{ 634 | if (target as f32 - n).abs() > 0.01 { continue; } 635 | } 636 | *ghost = *primary; 637 | *primary = (-(i as f32 / sr as f32), v, 0.0); 638 | } 639 | let offset = i as f32 / sr as f32; 640 | let pvel = apply_adsr(conf, primary.0 + offset) * primary.1; 641 | let gvel = apply_adsr(conf, ghost.0 + offset) * ghost.1; 642 | let adsr_vel = pvel.max(gvel) * maxmul + pvel.min(gvel) * minmul; 643 | let vel = lerp(1.0, adsr_vel, wet); 644 | 645 | buf.l[i] *= vel; 646 | buf.r[i] *= vel; 647 | } 648 | } 649 | primary.0 += len as f32 / sr as f32; 650 | ghost.0 += len as f32 / sr as f32; 651 | } 652 | 653 | #[allow(clippy::too_many_arguments)] 654 | fn band_pass_gen(buf: &mut Sample, len: usize, wet: f32, first: &mut bool, pass: bool, 655 | lgamma: f32, hgamma: f32, 656 | lprevl: &mut f32, lprevr: &mut f32, hprevl: &mut f32, hprevr: &mut f32){ 657 | if wet < 0.0001 { return; } 658 | if lgamma == 0.0 && hgamma == 0.0 { return; } 659 | let lmul = if lgamma == 0.0 { 0.0 } else { 1.0 }; 660 | let hmul = if hgamma == 0.0 { 0.0 } else { 1.0 }; 661 | let pass_mul = if pass { 1.0 } else { 0.0 }; 662 | let cut_mul = 1.0 - pass_mul; 663 | 664 | if *first { 665 | *lprevl = buf.l[0]; 666 | *lprevr = buf.r[0]; 667 | *hprevl = buf.l[0]; 668 | *hprevr = buf.r[0]; 669 | *first = false; 670 | } 671 | for i in 0..len{ 672 | let l = buf.l[i]; 673 | let r = buf.r[i]; 674 | let ll = *lprevl + lgamma * (l - *lprevl); 675 | let lr = *lprevr + lgamma * (r - *lprevr); 676 | let hl = *hprevl + hgamma * (l - *hprevl); 677 | let hr = *hprevr + hgamma * (r - *hprevr); 678 | *lprevl = ll; 679 | *lprevr = lr; 680 | *hprevl = hl; 681 | *hprevr = hr; 682 | let cutl = (lmul * ll + hmul * (l - hl)) * 0.5; 683 | let cutr = (lmul * lr + hmul * (r - hr)) * 0.5; 684 | let passl = l - cutl; 685 | let passr = r - cutl; 686 | buf.l[i] = cutl * cut_mul + passl * pass_mul; 687 | buf.r[i] = cutr * cut_mul + passr * pass_mul; 688 | } 689 | } 690 | 691 | -------------------------------------------------------------------------------- /src/floww.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use floww::{ Floww, read_floww_from_midi, FlowwPacket, unpacket }; 4 | use zen_colour::*; 5 | 6 | #[derive(Default)] 7 | pub struct FlowwBank{ 8 | sr: usize, 9 | bl: usize, 10 | frame: usize, 11 | block_index: usize, 12 | flowws: Vec, 13 | start_indices: Vec, 14 | names: HashMap, 15 | stream_list: Vec, 16 | } 17 | 18 | impl FlowwBank{ 19 | pub fn new(sr: usize, bl: usize) -> Self{ 20 | Self{ sr, bl, ..Default::default() } 21 | } 22 | 23 | pub fn reset(&mut self){ 24 | self.frame = 0; 25 | self.block_index = 0; 26 | self.flowws.clear(); 27 | self.start_indices.clear(); 28 | self.names.clear(); 29 | self.stream_list.clear(); 30 | } 31 | 32 | fn declare_floww(&mut self, name: String, floww: Floww) -> usize{ 33 | self.flowws.push(floww); 34 | self.start_indices.push(0); 35 | let index = self.flowws.len() - 1; 36 | self.names.insert(name, index); 37 | index 38 | } 39 | 40 | pub fn add_floww(&mut self, name: String, path: &str) -> Result<(), String>{ 41 | if let Ok(floww) = read_floww_from_midi(path){ 42 | self.declare_floww(name, floww); 43 | Ok(()) 44 | } else { 45 | Err(format!("{r}Could not read midi file: {b}\"{x}\"{r}.", 46 | r = RED, b = BLUE, x = path)) 47 | } 48 | } 49 | 50 | pub fn declare_stream(&mut self, name: String){ 51 | let index = self.declare_floww(name, vec![]); 52 | self.stream_list.push(index); 53 | } 54 | 55 | pub fn append_streams(&mut self, packets: Vec) -> Vec{ 56 | unpacket(&mut self.flowws, &self.names, packets) 57 | } 58 | 59 | pub fn trim_streams(&mut self){ 60 | for index in &self.stream_list{ 61 | let start_index = self.start_indices[*index]; 62 | self.flowws[*index].drain(..start_index); 63 | } 64 | } 65 | 66 | pub fn get_index(&self, name: &str) -> Option{ 67 | self.names.get(name).copied() 68 | } 69 | 70 | fn set_start_indices_to_frame(&mut self, t_frame: usize, do_skip: bool){ 71 | for (i, floww) in self.flowws.iter().enumerate(){ 72 | let skip = if do_skip{ self.start_indices[i] } 73 | else { 0 }; 74 | for (j, (_, t, _, _)) in floww.iter().enumerate().skip(skip){ 75 | if ((t * self.sr as f32) as usize) >= t_frame{ 76 | self.start_indices[i] = j; 77 | break; 78 | } 79 | } 80 | } 81 | } 82 | 83 | pub fn set_time(&mut self, t: usize){ 84 | self.set_start_indices_to_frame(t, false); 85 | self.frame = t; 86 | } 87 | 88 | pub fn set_time_to_next_block(&mut self){ 89 | self.frame += self.bl; 90 | self.set_start_indices_to_frame(self.frame, true); 91 | } 92 | 93 | pub fn start_block(&mut self, index: usize){ 94 | if index >= self.flowws.len() { return; } 95 | self.block_index = self.start_indices[index]; 96 | } 97 | 98 | // returns Option<(note, vel)> 99 | pub fn get_block_drum(&mut self, index: usize, offset_frame: usize) -> Option<(f32, f32)>{ 100 | if index >= self.flowws.len() { return None; } 101 | loop{ 102 | if self.block_index >= self.flowws[index].len(){ 103 | return None; 104 | } 105 | let next_event = self.flowws[index][self.block_index]; 106 | // this skips events when multiple on values are in the same time frame 107 | if ((next_event.1 * self.sr as f32) as usize) < self.frame + offset_frame{ 108 | self.block_index += 1; 109 | continue; 110 | } 111 | if ((next_event.1 * self.sr as f32) as usize) == self.frame + offset_frame{ 112 | self.block_index += 1; 113 | // Only send through if it's a hit, ignore note off's 114 | if next_event.3 > 0.001{ 115 | return Some((next_event.2, next_event.3)) 116 | } 117 | } else { 118 | return None; 119 | } 120 | } 121 | } 122 | 123 | // returns Vec<(on?, note, vel)> 124 | pub fn get_block_simple(&mut self, index: usize, offset_frame: usize) -> Vec<(bool, f32, f32)>{ 125 | let mut res = Vec::new(); 126 | if index >= self.flowws.len() { return res; } 127 | loop{ 128 | if self.block_index >= self.flowws[index].len(){ 129 | break; 130 | } 131 | let next_event = self.flowws[index][self.block_index]; 132 | if ((next_event.1 * self.sr as f32) as usize) == self.frame + offset_frame{ 133 | self.block_index += 1; 134 | let on = next_event.3 > 0.001; 135 | res.push((on, next_event.2, next_event.3)); 136 | } else { 137 | break; 138 | } 139 | } 140 | res 141 | } 142 | 143 | // returns Vec<(note, vel)> 144 | // pub fn get_block_continuous(&mut self, index: usize, offset_frame: usize) -> Vec<(f32, f32)>{ 145 | // } 146 | } 147 | 148 | -------------------------------------------------------------------------------- /src/graph.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | sample::{ Sample, SampleBank }, 3 | floww::{ FlowwBank }, 4 | extensions::*, 5 | lv2::Lv2Host, 6 | }; 7 | 8 | use std::collections::HashMap; 9 | 10 | use zen_colour::*; 11 | 12 | pub struct Graph{ 13 | vertices: Vec, 14 | edges: Vec>, 15 | names: Vec, 16 | name_map: HashMap, 17 | ran_status: Vec, 18 | output_vertex: Option, 19 | max_buffer_len: usize, 20 | sr: usize, 21 | t: usize, 22 | } 23 | 24 | impl Graph{ 25 | pub fn new(max_buffer_len: usize, sr: usize) -> Self{ 26 | Self{ 27 | vertices: Vec::new(), 28 | edges: Vec::new(), 29 | name_map: HashMap::new(), 30 | names: Vec::new(), 31 | ran_status: Vec::new(), 32 | output_vertex: None, 33 | max_buffer_len, 34 | sr, 35 | t: 0, 36 | } 37 | } 38 | 39 | pub fn reset(&mut self){ 40 | self.vertices.clear(); 41 | self.edges.clear(); 42 | self.name_map.clear(); 43 | self.names.clear(); 44 | self.ran_status.clear(); 45 | self.output_vertex = None; 46 | self.t = 0; 47 | } 48 | 49 | pub fn add(&mut self, node: Vertex, name: String){ 50 | self.vertices.push(node); 51 | self.ran_status.push(false); 52 | self.edges.push(Vec::new()); 53 | let n = self.vertices.len() - 1; 54 | self.name_map.insert(name.clone(), n); 55 | self.names.push(name); 56 | } 57 | 58 | fn connect_internal(&mut self, a: usize, b: usize) -> bool{ 59 | // basic checks 60 | if a == b { return false; } 61 | let len = self.vertices.len(); 62 | if a >= len { return false; } 63 | if b >= len { return false; } 64 | if !self.vertices[b].has_input() { return false; } 65 | // loop detection: 66 | fn has_loop(x: usize, b: usize, edges: &[Vec]) -> bool{ 67 | if x == b { return true; } 68 | for y in &edges[x]{ 69 | if has_loop(*y, b, edges) { return true; }; 70 | } 71 | false 72 | } 73 | if has_loop(a, b, &self.edges) { return false; } 74 | // connect a to b: a -> b, a into b 75 | // reverse: for such b we want to know which a's we should query 76 | self.edges[b].push(a); 77 | true 78 | } 79 | 80 | pub fn connect(&mut self, a: &str, b: &str) -> bool{ 81 | let a_res = self.name_map.get(a); 82 | let b_res = self.name_map.get(b); 83 | if a_res.is_none() { 84 | println!("{y}TermDaw: warning: vertex {b}\"{x}\"{y} cannot be found and thus can't be connected.", 85 | y = YELLOW, b = BLUE, x = a); 86 | return false; 87 | } 88 | if b_res.is_none() { 89 | println!("{y}TermDaw: warning: vertex {b}\"{x}\"{y} cannot be found and thus can't be connected to.", 90 | y = YELLOW, b = BLUE, x = b); 91 | return false; 92 | } 93 | let a_index = *a_res.unwrap(); 94 | let b_index = *b_res.unwrap(); 95 | self.connect_internal(a_index, b_index) 96 | } 97 | 98 | fn run_vertex( 99 | &mut self, t: usize, sb: &SampleBank, fb: &mut FlowwBank, host: &mut Lv2Host, 100 | index: usize, is_scan: bool 101 | ){ 102 | if index >= self.vertices.len() { return; } 103 | if self.ran_status[index] { return; } 104 | self.ran_status[index] = true; 105 | let edges = self.edges[index].clone(); 106 | for incoming in &edges{ 107 | self.run_vertex(t, sb, fb, host, *incoming, is_scan); 108 | } 109 | // Vertex buffers exist as long at the graph exists: we never delete vertices 110 | // Safe: we mutate vertex A (&mut A) and read data from incoming vertices [B] (&[B]) 111 | // TODO: maybe use arena? https://crates.io/crates/typed-arena 112 | unsafe { 113 | let ins = edges.iter().map(|incoming|{ 114 | &*(self.vertices[*incoming].read_buffer() as *const _) 115 | }).collect::>(); 116 | self.vertices[index].generate( 117 | (t, self.sr, self.max_buffer_len, is_scan), 118 | sb, fb, host, ins 119 | ); 120 | } 121 | } 122 | 123 | pub fn set_time(&mut self, time: usize){ 124 | self.t = time; 125 | for v in self.vertices.iter_mut(){ 126 | v.set_time(time); 127 | } 128 | } 129 | 130 | pub fn change_time(&mut self, delta: usize, plus: bool) -> usize{ 131 | let new_time = if plus { self.t + delta } 132 | else { self.t - delta.min(self.t) }; 133 | self.set_time(new_time); 134 | new_time 135 | } 136 | 137 | pub fn get_time(&self) -> usize{ 138 | self.t 139 | } 140 | 141 | pub fn set_output(&mut self, vert: &str) -> bool{ 142 | if let Some(index) = self.name_map.get(vert){ 143 | self.output_vertex = Some(*index); 144 | true 145 | } else { 146 | false 147 | } 148 | } 149 | 150 | pub fn check_graph(&self) -> bool{ 151 | let output = if let Some(out) = self.output_vertex{ out } 152 | else { 153 | println!("{}TermDaw: error: output vertex not found.", RED); 154 | return false; 155 | }; 156 | if self.edges[output].is_empty() && self.vertices[output].has_input(){ 157 | println!("{}TermDaw: error: output receives no inputs.", RED); 158 | return false; 159 | } 160 | let mut set = vec![false; self.vertices.len()]; 161 | fn find_connected_component(x: usize, edges: &[Vec], set: &mut Vec){ 162 | set[x] = true; 163 | for y in &edges[x]{ 164 | find_connected_component(*y, edges, set); 165 | } 166 | } 167 | find_connected_component(output, &self.edges, &mut set); 168 | for (i, x) in set.into_iter().enumerate(){ 169 | if x { continue; } 170 | println!("{y}TermDaw: warning: vertex {b}\"{x}\"{y} does not reach output.", 171 | y = YELLOW, b = BLUE, x = self.names[i]); 172 | } 173 | true 174 | } 175 | 176 | fn reset_ran_stati(&mut self){ 177 | for ran in &mut self.ran_status{ 178 | *ran = false; 179 | } 180 | } 181 | 182 | pub fn render( 183 | &mut self, sb: &SampleBank, fb: &mut FlowwBank, host: &mut Lv2Host 184 | ) -> Option<&Sample>{ 185 | self.reset_ran_stati(); 186 | if let Some(index) = self.output_vertex{ 187 | self.run_vertex(self.t, sb, fb, host, index, false); 188 | self.t += self.max_buffer_len; 189 | Some(self.vertices[index].read_buffer()) 190 | } else { 191 | None 192 | } 193 | } 194 | 195 | fn reset_scan_normalize_vertices(&mut self){ 196 | for vertex in self.vertices.iter_mut(){ 197 | vertex.ext.reset_scan_normalization(); 198 | } 199 | } 200 | 201 | fn apply_scan_normalize_vertices(&mut self){ 202 | for vertex in self.vertices.iter_mut(){ 203 | vertex.ext.apply_scan_normalization(); 204 | } 205 | } 206 | 207 | pub fn reset_normalize_vertices(&mut self){ 208 | for vertex in self.vertices.iter_mut(){ 209 | vertex.ext.reset_normalization(); 210 | } 211 | } 212 | 213 | pub fn print_normalization_values(&self){ 214 | for (i, vertex) in self.vertices.iter().enumerate(){ 215 | let nv = vertex.ext.get_normalization_value(); 216 | if nv > 0.0 { 217 | println!("{} {}: {}", MAGENTA, self.names[i], nv); 218 | } 219 | } 220 | } 221 | 222 | pub fn true_normalize_scan( 223 | &mut self, sb: &SampleBank, fb: &mut FlowwBank, host: &mut Lv2Host, chunks: usize 224 | ){ 225 | let i = if let Some(index) = self.output_vertex{ index } 226 | else { return; }; 227 | self.reset_scan_normalize_vertices(); 228 | fb.set_time(0); 229 | for j in 0..chunks { 230 | self.reset_ran_stati(); 231 | self.run_vertex(j * self.max_buffer_len, sb, fb, host, i, true); 232 | fb.set_time_to_next_block(); 233 | } 234 | self.apply_scan_normalize_vertices(); 235 | self.set_time(0); 236 | fb.set_time(0); 237 | } 238 | } 239 | // t, sr, len, is_scan 240 | pub type GenArgs = (usize, usize, usize, bool); 241 | 242 | pub struct Vertex{ 243 | buf: Sample, 244 | gain: f32, 245 | angle: f32, 246 | wet: f32, 247 | ext: VertexExt, 248 | } 249 | 250 | impl Vertex{ 251 | pub fn new(bl: usize, gain: f32, angle: f32, wet: f32, ext: VertexExt) -> Self{ 252 | Self{ 253 | buf: Sample::new(bl), 254 | gain, 255 | angle: angle.min(90.0).max(-90.0), 256 | wet: wet.min(1.0).max(0.0), 257 | ext, 258 | } 259 | } 260 | 261 | fn read_buffer(&self) -> &Sample{ 262 | &self.buf 263 | } 264 | 265 | // #[allow(clippy::too_many_arguments)] 266 | fn generate( 267 | &mut self, ga: GenArgs, sb: &SampleBank, fb: &mut FlowwBank, 268 | host: &mut Lv2Host, res: Vec<&Sample> 269 | ){ 270 | let len = self.buf.len().min(ga.2); 271 | let ga = (ga.0, ga.1, len, ga.3); 272 | self.ext.generate(ga, sb, fb, host, self.gain, self.angle, self.wet, &mut self.buf, res); 273 | } 274 | 275 | // Whether or not you can connect another vertex to (into) this one 276 | fn has_input(&self) -> bool{ 277 | self.ext.has_input() 278 | } 279 | 280 | pub fn set_time(&mut self, t: usize){ 281 | self.ext.set_time(t); 282 | } 283 | } 284 | 285 | -------------------------------------------------------------------------------- /src/lv2.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "lv2")] 2 | pub use lv2hm::Lv2Host as lv2h; 3 | #[cfg(feature = "lv2")] 4 | pub use lv2hm::AddPluginError; 5 | 6 | #[cfg(feature = "lv2")] 7 | pub type Lv2Host = lv2h; 8 | #[cfg(not(feature = "lv2"))] 9 | pub type Lv2Host = (); 10 | 11 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use mlua::prelude::*; 2 | use sdl2::audio::AudioSpecDesired; 3 | use zen_colour::*; 4 | 5 | mod sample; 6 | mod graph; 7 | mod floww; 8 | mod extensions; 9 | mod adsr; 10 | mod synth; 11 | mod config; 12 | mod state; 13 | mod bufferbank; 14 | mod ui_workflow; 15 | mod stream_workflow; 16 | mod lv2; 17 | 18 | use { 19 | sample::*, 20 | graph::*, 21 | floww::*, 22 | config::*, 23 | state::*, 24 | bufferbank::*, 25 | ui_workflow::*, 26 | stream_workflow::*, 27 | }; 28 | 29 | #[cfg(feature = "lv2")] 30 | use lv2::Lv2Host; 31 | 32 | use std::{ 33 | fs::File, 34 | io::Read, 35 | path::Path, 36 | }; 37 | 38 | fn main(){ 39 | let args: Vec = std::env::args().collect(); 40 | let wdir = if args.len() > 1{ 41 | args[1].to_owned() 42 | } else { 43 | "./".to_owned() 44 | }; 45 | let wpath = Path::new(&wdir); 46 | let config = Config::read(&wpath.join("project.toml")); 47 | 48 | println!("{s}TermDaw: loading {b}\"{x}\"{s} with \n\tbuffer_length = {b}{y}{s} \n\tproject_samplerate = {b}{z}{s} \n\tworkflow = {b}{w}{s} \n\tworkdir = {b}{v}{s} \n\tmain = {b}\"{u}\"{s}", 49 | s = DEFAULT, b = BLUE, 50 | x = config.project.name(), 51 | y = config.settings.buffer_length(), 52 | z = config.settings.project_samplerate(), 53 | w = config.settings.workflow(), 54 | v = wdir, 55 | u = config.settings.main); 56 | 57 | let main_path = wpath.join(&config.settings.main); 58 | let mut file = match File::open(main_path.clone()){ 59 | Ok(f) => f, 60 | Err(e) => { 61 | println!("{r}Error: could not open main lua file: {b}\"{x:#?}\"{r}.", 62 | r = RED, b = BLUE, x = main_path); 63 | println!("{}\t{}", RED, e); 64 | return; 65 | } 66 | }; 67 | let mut contents = String::new(); 68 | file.read_to_string(&mut contents).unwrap(); 69 | std::mem::drop(file); 70 | 71 | let proj_sr = config.settings.project_samplerate(); 72 | let buffer_len = config.settings.buffer_length(); 73 | let workflow = config.settings.workflow(); 74 | 75 | let mut state = State{ 76 | lua: Lua::new(), 77 | sb: SampleBank::new(proj_sr), 78 | g: Graph::new(config.settings.buffer_length(), proj_sr), 79 | #[cfg(feature = "lv2")] 80 | host: Lv2Host::new(1000, buffer_len * 2, proj_sr), // acount for l/r 81 | #[cfg(not(feature = "lv2"))] 82 | host: (), 83 | fb: FlowwBank::new(proj_sr, buffer_len), 84 | bb: BufferBank::new(), 85 | contents, 86 | config, 87 | loaded: false, 88 | cs: 0, 89 | render_sr: 48000, 90 | bd: 16, 91 | output_vertex: String::new(), 92 | output_file: String::from("outp.wav"), 93 | cur_samples: Vec::new(), 94 | cur_resources: Vec::new(), 95 | cur_lv2plugins: Vec::new(), 96 | cur_lv2params: Vec::new(), 97 | wdir, 98 | }; 99 | state.refresh(); 100 | 101 | let sdl_context = match sdl2::init(){ 102 | Ok(x) => x, 103 | Err(e) => { 104 | println!("{}Error: can't initialize sdl2 context.", RED); 105 | println!("{}\t{}", RED, e); 106 | return; 107 | } 108 | }; 109 | let audio_subsystem = match sdl_context.audio(){ 110 | Ok(x) => x, 111 | Err(e) => { 112 | println!("{}Error: can't get sdl audio subsystem.", RED); 113 | println!("{}\t{}", RED, e); 114 | return; 115 | } 116 | }; 117 | let desired_spec = AudioSpecDesired{ 118 | freq: Some(proj_sr as i32), 119 | channels: Some(2), 120 | samples: None, 121 | }; 122 | let device = match audio_subsystem.open_queue::(None, &desired_spec){ 123 | Ok(x) => x, 124 | Err(e) => { 125 | println!("{}Error: can't open sdl audio queue.", RED); 126 | println!("{}\t{}", RED, e); 127 | return; 128 | } 129 | }; 130 | 131 | match workflow{ 132 | WorkFlow::Manual => run_ui_workflow(proj_sr, buffer_len, state, device), 133 | WorkFlow::Stream => run_stream_workflow(proj_sr, buffer_len, state, device), 134 | } 135 | } 136 | 137 | -------------------------------------------------------------------------------- /src/sample.rs: -------------------------------------------------------------------------------- 1 | use std::collections::{ HashMap, HashSet }; 2 | 3 | use rubato::{ 4 | Resampler, SincFixedIn, SincInterpolationType, SincInterpolationParameters, WindowFunction 5 | }; 6 | use zen_colour::*; 7 | 8 | fn absmax(samples: &[f32]) -> f32{ 9 | absmaxlen(samples, std::usize::MAX) 10 | } 11 | 12 | fn absmaxlen(samples: &[f32], len: usize) -> f32{ 13 | samples.iter().take(len).fold(0.0, |max, s| { let a = s.abs(); if a > max { a } else { max } }) 14 | } 15 | 16 | fn mean_energy(samples: &[f32]) -> f32{ 17 | if samples.is_empty() { 18 | 0.0 19 | } else { 20 | samples.iter().map(|s| s.abs()).sum::() / samples.len() as f32 21 | } 22 | } 23 | 24 | #[derive(Clone, Default, PartialEq, Debug)] 25 | pub struct Sample{ 26 | pub l: Vec, 27 | pub r: Vec, 28 | } 29 | 30 | impl Sample{ 31 | pub fn new(bl: usize) -> Self{ 32 | Self{ 33 | l: vec![0.0; bl], 34 | r: vec![0.0; bl], 35 | } 36 | } 37 | 38 | pub fn from(l: Vec, r: Vec, method: SampleLoadMethod) -> Result{ 39 | match method{ 40 | SampleLoadMethod::Left => { 41 | if l.is_empty(){ 42 | return Err(format!("{r}TermDaw: Sample::from: l has length {b}0{r}.", 43 | r = RED, b = BLUE)); 44 | } 45 | Ok(Self { l: l.clone(), r: l }) 46 | }, 47 | SampleLoadMethod::Right => { 48 | if r.is_empty(){ 49 | return Err(format!("{r}TermDaw: Sample::from: r has length {b}0{r}.", 50 | r = RED, b = BLUE)); 51 | } 52 | Ok(Self { l: r.clone(), r }) 53 | }, 54 | SampleLoadMethod::Loudest => { 55 | let lm = mean_energy(&l); 56 | let rm = mean_energy(&r); 57 | if lm > rm{ 58 | Ok(Self { l: l.clone(), r: l }) 59 | } else { 60 | Ok(Self { l: r.clone(), r }) 61 | } 62 | }, 63 | _ => { 64 | if l.len() != r.len() { 65 | return Err(format!( 66 | "{r}TermDaw: Sample::from: l and r do not have the same length: {b}{llen}{r} and {b}{rlen}{r}.", 67 | r = RED, b = BLUE, llen = l.len(), rlen = r.len() 68 | )); 69 | } 70 | if l.is_empty(){ 71 | return Err(format!("{r}TermDaw: Sample::from: l and r have length {b}0{r}.", 72 | r = RED, b = BLUE)); 73 | } 74 | Ok(Self{ l, r }) 75 | } 76 | } 77 | } 78 | 79 | pub fn len(&self) -> usize{ 80 | self.l.len() 81 | } 82 | 83 | pub fn _is_empty(&self) -> bool{ 84 | self.l.is_empty() 85 | } 86 | 87 | pub fn zero(&mut self){ 88 | fn veczero(vec: &mut Vec){ 89 | for v in vec{ 90 | *v = 0.0; 91 | } 92 | } 93 | veczero(&mut self.l); 94 | veczero(&mut self.r); 95 | } 96 | 97 | pub fn apply_angle(&mut self, angle: f32, len: usize){ 98 | if angle.abs() < 0.001 { return; } 99 | let angle_rad = angle * 0.5 * 0.01745329; 100 | let l_amp = std::f32::consts::FRAC_1_SQRT_2 * (angle_rad.cos() + angle_rad.sin()); 101 | let r_amp = std::f32::consts::FRAC_1_SQRT_2 * (angle_rad.cos() - angle_rad.sin()); 102 | for i in 0..len{ 103 | self.l[i] *= l_amp; 104 | self.r[i] *= r_amp; 105 | } 106 | } 107 | 108 | pub fn apply_gain(&mut self, gain: f32, len: usize){ 109 | if (gain - 1.0).abs() < 0.001 { return; } 110 | for i in 0..len.min(self.len()) { 111 | self.l[i] *= gain; 112 | self.r[i] *= gain; 113 | } 114 | } 115 | 116 | pub fn scan_max(&self, len: usize) -> f32{ 117 | absmaxlen(&self.l, len).max(absmaxlen(&self.r, len)) 118 | } 119 | 120 | pub fn scale(&mut self, len: usize, scalar: f32){ 121 | self.l.iter_mut().take(len).for_each(|sample| *sample *= scalar); 122 | self.r.iter_mut().take(len).for_each(|sample| *sample *= scalar); 123 | } 124 | 125 | pub fn normalize(&mut self, len: usize){ 126 | let len = len.min(self.len()); 127 | let max = self.scan_max(len); 128 | let scalar = 1.0 / max; 129 | self.scale(len, scalar); 130 | } 131 | 132 | pub fn normalize_seperate(&mut self){ 133 | let scalel = 1.0 / absmax(&self.l); 134 | let scaler = 1.0 / absmax(&self.r); 135 | self.l.iter_mut().for_each(|sample| *sample *= scalel); 136 | self.r.iter_mut().for_each(|sample| *sample *= scaler); 137 | } 138 | 139 | pub fn mix_down(&mut self){ 140 | let l = std::mem::take(&mut self.l); 141 | let r = std::mem::take(&mut self.r); 142 | let mut mix = l.into_iter().zip(r).map(|(l,r)| l + r).collect::>(); 143 | let scale = 1.0 / absmax(&mix); 144 | mix.iter_mut().for_each(|s| *s *= scale); 145 | self.l.clone_from(&mix); 146 | self.r = mix; 147 | } 148 | 149 | //Not for chunks! 150 | pub fn resample(&self, from: usize, to: usize) -> Result{ 151 | // no idea what is means but comes from the example lol 152 | let params = SincInterpolationParameters { 153 | sinc_len: 256, 154 | f_cutoff: 0.95, 155 | interpolation: SincInterpolationType::Linear, 156 | oversampling_factor: 256, 157 | window: WindowFunction::BlackmanHarris2, 158 | }; 159 | let resampler = SincFixedIn::::new( 160 | to as f64 / from as f64, 161 | 1.0, 162 | params, self.len(), 2 163 | ); 164 | let mut resampler = match resampler { 165 | Ok(r) => r, 166 | Err(_) => return Err(String::from("error: sample: could not construct hound resampler.")), 167 | }; 168 | let waves_in = vec![self.l.clone(), self.r.clone()]; 169 | let mut waves_out = resampler.process(&waves_in, None).unwrap(); 170 | let l = std::mem::take(&mut waves_out[0]); 171 | let r = std::mem::take(&mut waves_out[1]); 172 | Ok(Self{ 173 | l, r 174 | }) 175 | } 176 | 177 | pub fn interleave(self) -> Vec{ 178 | let mut res = Vec::new(); 179 | for i in 0..self.len(){ 180 | res.push(self.l[i]); 181 | res.push(self.r[i]); 182 | } 183 | res 184 | } 185 | } 186 | 187 | pub struct SampleBank{ 188 | sample_rate: usize, 189 | samples: Vec, 190 | names: HashMap, 191 | max_sr: usize, 192 | max_bd: usize, 193 | marked: HashSet, 194 | } 195 | 196 | #[derive(Clone,Copy,PartialEq,Eq)] 197 | pub enum SampleLoadMethod{ Stereo, Left, Right, Loudest, Norm, Mix } 198 | 199 | impl SampleLoadMethod{ 200 | pub fn from(string: &str) -> Self{ 201 | match string{ 202 | "left" => SampleLoadMethod::Left, 203 | "right" => SampleLoadMethod::Right, 204 | "loudest" => SampleLoadMethod::Loudest, 205 | "normalize-seperate" => SampleLoadMethod::Norm, 206 | "mix-down" => SampleLoadMethod::Mix, 207 | _ => SampleLoadMethod::Stereo, 208 | } 209 | } 210 | } 211 | 212 | impl SampleBank{ 213 | pub fn new(sample_rate: usize) -> Self{ 214 | Self{ 215 | sample_rate, 216 | samples: Vec::new(), 217 | names: HashMap::new(), 218 | max_sr: 0, 219 | max_bd: 0, 220 | marked: HashSet::new(), 221 | } 222 | } 223 | 224 | pub fn add(&mut self, name: String, file: &str, method: SampleLoadMethod) -> Result<(), String>{ 225 | if self.names.contains_key(&name) { 226 | return Err(format!( 227 | "{r}TermDaw: SampleBank: there is already a sample with name {b}\"{n}\"{r} present.", 228 | r = RED, b = BLUE, n = name 229 | )); 230 | } 231 | let mut reader = if let Ok(reader) = hound::WavReader::open(file){ 232 | reader 233 | } else { 234 | return Err(format!( 235 | "{r}TermDaw: SampleBank: could not open file {b}\"{f}\"{r}.", 236 | r = RED, b = BLUE, f = file 237 | )); 238 | }; 239 | let specs = reader.spec(); 240 | if method == SampleLoadMethod::Stereo && specs.channels != 2{ 241 | return Err(format!( 242 | "{r}TermDaw: SampleBank: only 2 channel samples are supported for stereo samples, found {b}{s}{r} channels.", 243 | r = RED, b = BLUE, s = specs.channels 244 | )); 245 | } 246 | if method != SampleLoadMethod::Stereo && specs.channels > 2{ 247 | return Err(format!( 248 | "{r}TermDaw: SampleBank: only 1,2 channel samples are supported for left or right samples, found {b}{s}{r} channels.", 249 | r = RED, b = BLUE, s = specs.channels 250 | )); 251 | } 252 | let sr = specs.sample_rate as usize; 253 | let bd = specs.bits_per_sample; 254 | self.max_sr = self.max_sr.max(sr); 255 | self.max_bd = self.max_bd.max(bd as usize); 256 | if sr > self.sample_rate { 257 | println!( 258 | "{y}TermDaw: warning: sample {b}\"{n}\"{y} has a higher samplerate({b}{sr}{y}) than the project({b}{psr}{y}).", 259 | y = YELLOW, b = BLUE, n = name, sr = sr, psr = self.sample_rate 260 | ); 261 | } 262 | let mut linear = Vec::new(); 263 | if specs.sample_format == hound::SampleFormat::Float{ 264 | for s in reader.samples::(){ 265 | if s.is_err() { continue; } 266 | linear.push(s.unwrap()); 267 | } 268 | } else { 269 | //let max = ((1 << bd) / 2 - 1) as f32; 270 | for s in reader.samples::(){ 271 | if s.is_err() { continue; } 272 | linear.push(s.unwrap() as f32); 273 | } 274 | } 275 | let mut l = Vec::new(); 276 | let mut r = Vec::new(); 277 | if specs.channels == 1{ 278 | if method == SampleLoadMethod::Left{ 279 | l = linear; 280 | } else { 281 | r = linear; 282 | } 283 | } else { 284 | let half_len = linear.len() / 2; 285 | for i in 0..half_len{ 286 | l.push(linear[i * 2]); 287 | r.push(linear[i * 2 + 1]); 288 | } 289 | if linear.len() > half_len * 2{ 290 | l.push(linear[linear.len() - 1]); 291 | } 292 | } 293 | let mut sample = match Sample::from(l, r, method){ 294 | Ok(sample) => { sample }, 295 | Err(e) => { return Err(e); } 296 | }; 297 | if method == SampleLoadMethod::Norm{ 298 | sample.normalize_seperate(); 299 | } else if method == SampleLoadMethod::Mix{ 300 | sample.mix_down(); 301 | } else { 302 | sample.normalize(usize::MAX); 303 | } 304 | // resampling 305 | if sr != self.sample_rate{ // need to resample 306 | match sample.resample(sr, self.sample_rate) { 307 | Ok(s) => sample = s, 308 | Err(e) => return Err(e), 309 | } 310 | } 311 | self.samples.push(sample); 312 | self.names.insert(name, self.samples.len() - 1); 313 | Ok(()) 314 | } 315 | 316 | pub fn mark_dead(&mut self, name: &str){ 317 | if let Some(index) = self.names.get(name){ 318 | self.marked.insert(*index); 319 | } 320 | } 321 | 322 | pub fn refresh(&mut self){ 323 | if self.marked.is_empty() { return; } 324 | let mut new_map = HashMap::new(); 325 | let mut new_vec = Vec::new(); 326 | let names = std::mem::take(&mut self.names); 327 | for (name, index) in names{ 328 | if self.marked.contains(&index) { continue; } 329 | let sample = std::mem::take(&mut self.samples[index]); 330 | new_vec.push(sample); 331 | new_map.insert(name, new_vec.len() - 1); 332 | } 333 | self.names = new_map; 334 | self.samples = new_vec; 335 | self.marked.clear(); 336 | } 337 | 338 | pub fn get_index(&self, name: &str) -> Option{ 339 | self.names.get(name).copied() 340 | } 341 | 342 | pub fn get_sample(&self, index: usize) -> &Sample{ 343 | &self.samples[index] 344 | } 345 | 346 | pub fn get_max_sr_bd(&self) -> (usize, usize){ 347 | (self.max_sr, self.max_bd) 348 | } 349 | } 350 | 351 | -------------------------------------------------------------------------------- /src/state.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | extensions::*, 3 | synth::*, 4 | adsr::*, 5 | graph::*, 6 | floww::*, 7 | config::*, 8 | sample::*, 9 | bufferbank::*, 10 | lv2::*, 11 | }; 12 | 13 | use rubato::{ 14 | Resampler, SincFixedIn, SincInterpolationType, SincInterpolationParameters, WindowFunction 15 | }; 16 | use fnrs::vecs; 17 | use mlua::prelude::*; 18 | use sampsyn::*; 19 | use zen_colour::*; 20 | 21 | use std::{ 22 | fs::File, 23 | io::Read, 24 | path::Path, 25 | }; 26 | 27 | pub struct State{ 28 | pub lua: Lua, 29 | pub sb: SampleBank, 30 | pub g: Graph, 31 | pub host: Lv2Host, 32 | pub fb: FlowwBank, 33 | pub bb: BufferBank, 34 | pub config: Config, 35 | pub contents: String, 36 | pub loaded: bool, 37 | pub cs: usize, 38 | pub render_sr: usize, 39 | pub bd: usize, 40 | pub output_vertex: String, 41 | pub output_file: String, 42 | pub cur_samples: Vec<(String, String, String)>, 43 | pub cur_resources: Vec<(String, String)>, 44 | pub cur_lv2plugins: Vec<(String, String)>, 45 | pub cur_lv2params: Vec<(String, String, f32)>, 46 | pub wdir: String, 47 | } 48 | 49 | impl State{ 50 | pub fn refresh(&mut self) { 51 | self.loaded = false; 52 | let psr = self.config.settings.project_samplerate(); 53 | let bl = self.config.settings.buffer_length(); 54 | 55 | let mut file = if let Ok(f) = File::open( 56 | Path::new(&self.wdir).join(&self.config.settings.main) 57 | ) { f } 58 | else { 59 | println!("{}Can't open main lua file!", RED); 60 | return; 61 | }; 62 | self.contents.clear(); 63 | if let Err(e) = file.read_to_string(&mut self.contents){ 64 | println!("{}Could not read main lua file!", RED); 65 | println!("\t{}", e); 66 | return; 67 | } 68 | 69 | vecs!( 70 | new_samples, new_resources, new_lv2plugins, new_lv2params, midis, streams, 71 | sums, norms, sampleloops, samplemultis, samplelerps, debugsines, synths, sampsyns, 72 | lv2fxs, adsrs, 73 | bandpasses, 74 | edges 75 | ); 76 | 77 | let mut cs = self.cs; 78 | let mut render_sr = self.render_sr; 79 | let mut bd = self.bd; 80 | let mut output_file = std::mem::take(&mut self.output_file); 81 | let mut output_vertex = std::mem::take(&mut self.output_vertex); 82 | 83 | let luares = self.lua.scope(|scope| { 84 | // ---- Macros 85 | macro_rules! seed{ 86 | ($name:expr, $stype:ty, $vec:ident) => { 87 | #[allow(clippy::type_complexity)] 88 | self.lua.globals().set($name, scope.create_function_mut(|_, seed: $stype| { 89 | $vec.push(seed); 90 | Ok(()) 91 | })?)?; 92 | }; 93 | } 94 | macro_rules! setter{ 95 | ($name:expr, $stype:ty, $var:ident) => { 96 | self.lua.globals().set($name, scope.create_function_mut(|_, arg: $stype| { 97 | $var = arg; 98 | Ok(()) 99 | })?)?; 100 | }; 101 | } 102 | // ---- Settings 103 | self.lua.globals().set("set_length", scope.create_function_mut(|_, seconds: f32| { 104 | cs = (psr as f32 * seconds / bl as f32).ceil() as usize; 105 | Ok(()) 106 | })?)?; 107 | setter!("set_render_samplerate", usize, render_sr); 108 | setter!("set_render_bitdepth", usize, bd); 109 | setter!("set_output_file", String, output_file); 110 | // ---- Resources 111 | // load_sample(name, file) 112 | seed!("load_sample", (String, String, String), new_samples); 113 | // load_resource(name, file) 114 | seed!("load_resource", (String, String), new_resources); 115 | // load_midi(name, file) 116 | seed!("load_midi_floww", (String, String), midis); 117 | // declare_stream(name) 118 | seed!("declare_stream", String, streams); 119 | // load_lv2(name, uri) 120 | seed!("load_lv2", (String, String), new_lv2plugins); 121 | // parameter(plugin, name, value) 122 | seed!("parameter", (String, String, f32), new_lv2params); 123 | // ---- Graph 124 | // add_sum(name, gain, angle) 125 | seed!("add_sum", (String, f32, f32), sums); 126 | // add_normalize(name, gain, angle) 127 | seed!("add_normalize", (String, f32, f32), norms); 128 | // add_sampleloop(name, gain, angle, sample) 129 | seed!("add_sampleloop", (String, f32, f32, String), sampleloops); 130 | // add_sample_multi(name, gain, angle, sample, floww, note) 131 | seed!("add_sample_multi", (String, f32, f32, String, String, i32), samplemultis); 132 | // add_sample_lerp(name, gain, angle, sample, floww, note, lerp_len) 133 | seed!("add_sample_lerp", (String, f32, f32, String, String, i32, i32), samplelerps); 134 | // add_debug_sine(name, gain, angle, floww) 135 | seed!("add_debug_sine", (String, f32, f32, String), debugsines); 136 | // add_synth(name, gain, angle, floww, square_vel, square_z, square_adsr_conf, 137 | // topflat_vel, topflat_z, topflat_adsr_conf, triangle_vel, triangle_adsr_conf) 138 | seed!( 139 | "add_synth", 140 | (String, f32, f32, String, f32, f32, Vec, f32, f32, Vec, f32, Vec), 141 | synths 142 | ); 143 | // add_sampsyn(name, gain, angle, floww, adsr_conf, resource) 144 | seed!("add_sampsyn", (String, f32, f32, String, Vec, String), sampsyns); 145 | // add_lv2fx(name, gain, angle, wet, plugin) 146 | seed!("add_lv2fx", (String, f32, f32, f32, String), lv2fxs); 147 | // add_adsr(name, gain, angle, wet, floww, use_off, note, adsr_conf) 148 | seed!("add_adsr", (String, f32, f32, f32, String, bool, bool, i32, Vec), adsrs); 149 | // add_bandpass(name, gain, angle, wet, cut_off_hz_low, cut_off_hz_high, pass) 150 | seed!("add_bandpass", (String, f32, f32, f32, f32, f32, bool), bandpasses); 151 | // connect(name, name) 152 | seed!("connect", (String, String), edges); 153 | // ---- Output 154 | self.lua.globals().set("set_output", scope.create_function_mut(|_, out: String| { 155 | output_vertex = out; 156 | Ok(()) 157 | })?)?; 158 | self.lua.load(&self.contents).exec() 159 | }); 160 | if let Err(e) = luares{ 161 | println!("{}Could not execute lua code!", RED); 162 | println!("\t{}", e); 163 | return; 164 | } 165 | 166 | self.cs = cs; 167 | self.bd = bd; 168 | self.render_sr = render_sr; 169 | self.output_file = output_file; 170 | self.output_vertex = output_vertex; 171 | 172 | fn diff(old: &[T], new: &[T]) -> (Vec, Vec){ 173 | let mut adds = Vec::new(); 174 | for t in new{ 175 | if !old.contains(t){ 176 | adds.push(t.clone()); 177 | } 178 | } 179 | let mut removes = Vec::new(); 180 | for t in old{ 181 | if !new.contains(t){ 182 | removes.push(t.clone()); 183 | } 184 | } 185 | (adds, removes) 186 | } 187 | 188 | macro_rules! do_excluding{ 189 | ($to_exclude:expr, $new:expr, $cur:expr) => { 190 | if !$to_exclude.is_empty(){ 191 | for name in $to_exclude{ 192 | $new.retain(|i| i.0 != name); 193 | } 194 | $cur = $new; 195 | return; 196 | } 197 | $cur = $new; 198 | }; 199 | } 200 | 201 | // samples may be long, try not to reallocate to much shit 202 | let (pos, neg) = diff(&self.cur_samples, &new_samples); 203 | for (name, _, _) in neg { 204 | println!("{s}Info: sample {b}\"{x}\"{s} will be removed from the sample bank.", 205 | s = DEFAULT, b = BLUE, x = name); 206 | self.sb.mark_dead(&name); 207 | } 208 | println!("{}Status: refreshing sample bank.", DEFAULT); 209 | self.sb.refresh(); 210 | let mut to_exclude = Vec::new(); 211 | for (name, file, method) in pos { 212 | println!("{s}Status: adding sample {b}\"{x}\"{s} to the sample bank.", 213 | s = DEFAULT, b = BLUE, x = name); 214 | if let Err(msg) = self.sb.add(name.clone(), &file, SampleLoadMethod::from(&method)){ 215 | println!("{}{}", RED, msg); 216 | to_exclude.push(name); 217 | } 218 | } 219 | do_excluding!(to_exclude, new_samples, self.cur_samples); 220 | 221 | // Same for resources 222 | let (pos, neg) = diff(&self.cur_resources, &new_resources); 223 | for (name, _) in neg { 224 | println!("{s}Info: resource {b}\"{x}\"{s} will be removed.", 225 | s = DEFAULT, b = BLUE, x = name); 226 | self.bb.mark_dead(&name); 227 | } 228 | println!("{}Status: refreshing resources.", DEFAULT); 229 | self.bb.refresh(); 230 | let mut to_exclude = Vec::new(); 231 | for (name, file) in pos{ 232 | if let Err(msg) = self.bb.add(name.clone(), &file){ 233 | println!("{}{}", RED, msg); 234 | to_exclude.push(name); 235 | } 236 | } 237 | do_excluding!(to_exclude, new_resources, self.cur_resources); 238 | 239 | // Just reload all midi, so you can easily import newly inplace generated files 240 | self.fb.reset(); 241 | for (name, file) in midis{ 242 | if let Err(msg) = self.fb.add_floww(name, &file){ 243 | println!("{}{}", RED, msg); 244 | return; 245 | } 246 | } 247 | for name in streams{ 248 | println!("{}", name); 249 | self.fb.declare_stream(name); 250 | } 251 | 252 | // Also don't recreate plugins 253 | // TODO: make renaming possible 254 | #[cfg(feature = "lv2")] 255 | { 256 | let (pos, neg) = diff(&self.cur_lv2plugins, &new_lv2plugins); 257 | for (name, _) in neg { // TODO: make plugins removable 258 | self.host.remove_plugin(&name); 259 | } 260 | let mut to_exclude = Vec::new(); 261 | for (name, uri) in pos { 262 | if let Err(e) = self.host.add_plugin(&uri, name.clone()){ 263 | println!( 264 | "{r}Couldn't load Lv2 plugin with name: {b}\"{n}\"{r} and uri: {b}\"{u}\"{r}.", 265 | r = RED, b = BLUE, n = name, u = uri 266 | ); 267 | match e{ 268 | AddPluginError::CapacityReached => { 269 | println!("{}\tCapacity reached!", RED); 270 | }, 271 | AddPluginError::WorldIsNull => { 272 | println!("{}\tWorld is null!", RED); 273 | }, 274 | AddPluginError::PluginIsNull => { 275 | println!("{}\tPlugin is null!", RED); 276 | }, 277 | AddPluginError::MoreThanTwoInOrOutAudioPorts(ins, outs) => { 278 | println!( 279 | "{}\tPlugin has more than two input or output audio ports!", 280 | RED 281 | ); 282 | println!( 283 | "{r}\tAudio inputs: {b}{i}{r}, audio outputs: {b}{o}", 284 | r = RED, b = BLUE, i = ins, o = outs 285 | ); 286 | }, 287 | AddPluginError::MoreThanOneAtomPort(atomports) => { 288 | println!( 289 | "{r}\tPlugin has more than one atom ports! Atom ports: {b}{a}{r}.", 290 | r = RED, b = BLUE, a = atomports 291 | ); 292 | }, 293 | AddPluginError::PortNeitherInputOrOutput => { 294 | println!( 295 | "{}\tPlugin has a port that is neither input or output.", 296 | RED 297 | ); 298 | }, 299 | AddPluginError::PortNeitherControlOrAudioOrOptional => { 300 | println!( 301 | "{}\tPlugin has a port that is neither control, audio or optional.", 302 | RED 303 | ); 304 | }, 305 | } 306 | to_exclude.push(name.clone()); 307 | } 308 | println!("{s}Info: added plugin {b}{n}{s} with uri {b}{u}{s}.", 309 | s = DEFAULT, b = BLUE, n = name, u = uri); 310 | } 311 | do_excluding!(to_exclude, new_lv2plugins, self.cur_lv2plugins); 312 | 313 | // need diff to see what params we need to reset 314 | let (pos, neg) = diff(&self.cur_lv2params, &new_lv2params); 315 | for (plugin, name, _) in neg { // TODO: make params resetable in Lv2hm 316 | self.host.reset_value(&plugin, &name); 317 | } 318 | for (plugin, name, value) in pos{ 319 | self.host.set_value(&plugin, &name, value); 320 | } 321 | 322 | self.cur_lv2params = new_lv2params; 323 | } 324 | 325 | // just rebuild the damn thing, if it becomes problematic i'll do something about it, 326 | // probably :) 327 | println!("{}Status: rebuilding graph.", DEFAULT); 328 | self.g.reset(); 329 | macro_rules! get_index{ 330 | ($obj:expr, $arg:expr, $name:expr, $category:expr) => { 331 | match $obj.get_index($arg){ 332 | Some(i) => i, 333 | None => { 334 | println!("{}Could not get {} index for vertex {}\"{}\"{}.", 335 | RED, $category, BLUE, $name, DEFAULT); 336 | return; 337 | } 338 | } 339 | } 340 | } 341 | for (name, gain, angle) in &sums { 342 | self.g.add(Vertex::new(bl, *gain, *angle, 0.0, VertexExt::sum()), name.to_owned()); 343 | } 344 | for (name, gain, angle) in &norms { 345 | self.g.add( 346 | Vertex::new(bl, *gain, *angle, 0.0, VertexExt::normalize()), name.to_owned() 347 | ); 348 | } 349 | for (name, gain, angle, sample) in &sampleloops { 350 | let index = get_index!(self.sb, sample, name, "sample"); 351 | self.g.add( 352 | Vertex::new(bl, *gain, *angle, 0.0, VertexExt::sample_loop(index)), name.to_owned() 353 | ); 354 | } 355 | for (name, gain, angle, sample, floww, note) in &samplemultis { 356 | let sample = get_index!(self.sb, sample, name, "sample"); 357 | let floww = get_index!(self.fb, floww, name, "floww"); 358 | let note = if note < &0 { None } 359 | else { Some(*note as usize) }; 360 | self.g.add( 361 | Vertex::new(bl, *gain, *angle, 0.0, VertexExt::sample_multi(sample, floww, note)), 362 | name.to_owned() 363 | ); 364 | } 365 | for (name, gain, angle, sample, floww, note, lerp_len) in &samplelerps { 366 | let sample = get_index!(self.sb, sample, name, "sample"); 367 | let floww = get_index!(self.fb, floww, name, "floww"); 368 | let note = if note < &0 { None } 369 | else { Some(*note as usize) }; 370 | let lerp_len = (*lerp_len).max(0) as usize; 371 | self.g.add( 372 | Vertex::new( 373 | bl, *gain, *angle, 0.0, VertexExt::sample_lerp(sample, floww, note, lerp_len) 374 | ), 375 | name.to_owned() 376 | ); 377 | } 378 | for (name, gain, angle, floww) in &debugsines { 379 | let floww = get_index!(self.fb, floww, name, "floww"); 380 | self.g.add( 381 | Vertex::new(bl, *gain, *angle, 0.0, VertexExt::debug_sine(floww)), 382 | name.to_owned() 383 | ); 384 | } 385 | for ( 386 | name, gain, angle, floww, sq_vel, sq_z, sq_arr, tf_vel, tf_z, tf_arr, tr_vel, tr_arr 387 | ) in &synths 388 | { 389 | let floww = get_index!(self.fb, floww, name, "floww"); 390 | let parse_adsr_conf = |arr| if let Some(config) = build_adsr_conf(arr){ 391 | config 392 | } else { 393 | panic!("ADSR config must have 6 or 9 elements"); 394 | }; 395 | let sq_adsr = parse_adsr_conf(sq_arr); 396 | let tf_adsr = parse_adsr_conf(tf_arr); 397 | let tr_adsr = parse_adsr_conf(tr_arr); 398 | self.g.add(Vertex::new(bl, *gain, *angle, 0.0, 399 | VertexExt::synth(floww, 400 | OscConf::new(*sq_vel, sq_z.max(0.0001), sq_adsr), 401 | OscConf::new(*tf_vel, *tf_z, tf_adsr), 402 | OscConf::new(*tr_vel, 0.0, tr_adsr))), 403 | name.to_owned() 404 | ); 405 | } 406 | for (name, gain, angle, floww, adsr_conf, resource) in &sampsyns { 407 | let floww = get_index!(self.fb, floww, name, "floww"); 408 | 409 | let adsr = if let Some(config) = build_adsr_conf(adsr_conf){ config } 410 | else { panic!("ADSR config must have 6 or 9 elements"); }; 411 | 412 | let buf_ind = if let Some(i) = self.bb.get_index(resource){ i } 413 | else { panic!("Could not find resource named {}!", resource); }; 414 | 415 | let table = if let Some(t) = parse_wavetable_from_buffer(self.bb.get_buffer(buf_ind)) { t } 416 | else { 417 | println!( 418 | "{s}Could not parse wavetable from resource {b}\"{r}\"{s}, using default table!", 419 | s = DEFAULT, b = BLUE, r = resource 420 | ); 421 | WaveTable::default() 422 | }; 423 | 424 | self.g.add(Vertex::new(bl, *gain, *angle, 0.0, 425 | VertexExt::sampsyn(floww, adsr, table)), name.to_owned()); 426 | } 427 | #[cfg(feature = "lv2")] 428 | { 429 | for (name, gain, angle, wet, plugin) in &lv2fxs { 430 | let index = get_index!(self.host, plugin, name, "plugin"); 431 | self.g.add( 432 | Vertex::new(bl, *gain, *angle, *wet, VertexExt::lv2fx(index)), 433 | name.to_owned() 434 | ); 435 | } 436 | } 437 | for (name, gain, angle, wet, floww, use_off, use_max, note, conf_arr) in &adsrs { 438 | let floww = get_index!(self.fb, floww, name, "floww"); 439 | let note = if note < &0 { None } 440 | else { Some(*note as usize) }; 441 | let conf = if let Some(config) = build_adsr_conf(conf_arr){ 442 | config 443 | } else { 444 | panic!("ADSR config must have 6 or 9 elements"); 445 | }; 446 | self.g.add( 447 | Vertex::new( 448 | bl, *gain, *angle, *wet, VertexExt::adsr(*use_off, *use_max, conf, note, floww) 449 | ), 450 | name.to_owned() 451 | ); 452 | } 453 | for (name, gain, angle, wet, cut_off_hz_low, cut_off_hz_high, pass) in &bandpasses { 454 | self.g.add(Vertex::new(bl, *gain, *angle, *wet, 455 | VertexExt::band_pass(*cut_off_hz_low, *cut_off_hz_high, *pass, psr)), 456 | name.to_owned()); 457 | } 458 | 459 | for (a, b) in &edges { self.g.connect(a, b); } 460 | 461 | self.g.set_output(&self.output_vertex); 462 | if !self.g.check_graph(){ 463 | println!("{}TermDaw: graph check failed!", RED); 464 | return; 465 | } 466 | 467 | self.g.reset_normalize_vertices(); 468 | 469 | println!("{}Ok: refreshed.", GREEN); 470 | self.loaded = true; 471 | } 472 | 473 | pub fn scan_exact(&mut self){ 474 | self.g.true_normalize_scan(&self.sb, &mut self.fb, &mut self.host, self.cs); 475 | } 476 | 477 | pub fn render(&mut self) { 478 | println!("{}Status: started rendering", DEFAULT); 479 | let psr = self.config.settings.project_samplerate(); 480 | let bl = self.config.settings.buffer_length(); 481 | 482 | let (msr, mbd) = self.sb.get_max_sr_bd(); 483 | if psr > self.render_sr{ 484 | println!( 485 | "{y}TermDaw: warning: render will down sample from {b}{p}{y}(project s.r.) to {b}{r}{y}.", 486 | y = YELLOW, b = BLUE, p = psr, r = self.render_sr 487 | ); 488 | } 489 | if msr > self.render_sr{ 490 | println!( 491 | "{y}TermDaw: warning: render will down sample from peak input quality({b}{m}{y}) to {b}{r}{y}.", 492 | y = YELLOW, b = BLUE, m = msr, r = self.render_sr 493 | ); 494 | } 495 | if !(self.bd == 8 || self.bd == 16 || self.bd == 24 || self.bd == 32) { 496 | println!( 497 | "{r}Bitdepth of {b}{bd}{r} not supported: choose bitdepth in {{8, 16, 24, 32}}.", 498 | r = RED, b = BLUE, bd = self.bd 499 | ); 500 | return; 501 | } 502 | if mbd > self.bd{ 503 | println!( 504 | "{y}TermDaw: warning: render will lose bitdepth from peak input quality({b}{m}{y} bits) to {b}{bd}{y} bits", 505 | y = YELLOW, b = BLUE, m = mbd, bd = self.bd 506 | ); 507 | } 508 | let spec = hound::WavSpec{ 509 | channels: 2, 510 | sample_rate: self.render_sr as u32, 511 | bits_per_sample: self.bd as u16, 512 | sample_format: hound::SampleFormat::Int, 513 | }; 514 | let mut writer = hound::WavWriter::create(self.output_file.clone(), spec).unwrap(); 515 | let amplitude = if self.bd < 32 { ((1 << (self.bd - 1)) - 1) as f32 } 516 | else { i32::MAX as f32 }; 517 | fn write_16s( 518 | writer: &mut hound::WavWriter, l: &[f32], r: &[f32], len: usize, amplitude: f32 519 | ){ 520 | for i in 0..len{ 521 | writer.write_sample((l[i] * amplitude) as i16).unwrap(); 522 | writer.write_sample((r[i] * amplitude) as i16).unwrap(); 523 | } 524 | } 525 | fn write_32s( 526 | writer: &mut hound::WavWriter, l: &[f32], r: &[f32], len: usize, amplitude: f32 527 | ){ 528 | for i in 0..len{ 529 | writer.write_sample((l[i] * amplitude) as i32).unwrap(); 530 | writer.write_sample((r[i] * amplitude) as i32).unwrap(); 531 | } 532 | } 533 | if psr > self.render_sr{ 534 | let params = SincInterpolationParameters { 535 | sinc_len: 256, 536 | f_cutoff: 0.95, 537 | interpolation: SincInterpolationType::Linear, 538 | oversampling_factor: 256, 539 | window: WindowFunction::BlackmanHarris2, 540 | }; 541 | let mut resampler = SincFixedIn::::new( 542 | self.render_sr as f64 / psr as f64, 543 | 1.0, params, bl, 2 544 | ).expect("error: render: could not construct hound resampler"); 545 | for _ in 0..self.cs{ 546 | let chunk = self.g.render(&self.sb, &mut self.fb, &mut self.host); 547 | if chunk.is_none() { continue; } 548 | let chunk = chunk.unwrap(); 549 | let waves_in = vec![chunk.l.clone(), chunk.r.clone()]; 550 | let waves_out = resampler.process(&waves_in, None).unwrap(); 551 | if self.bd > 16 { 552 | write_32s( 553 | &mut writer, &waves_out[0], &waves_out[1], waves_out[0].len(), amplitude 554 | ); 555 | } else { 556 | write_16s( 557 | &mut writer, &waves_out[0], &waves_out[1], waves_out[0].len(), amplitude 558 | ); 559 | } 560 | self.fb.set_time_to_next_block(); 561 | } 562 | } else { 563 | for _ in 0..self.cs{ 564 | let chunk = self.g.render(&self.sb, &mut self.fb, &mut self.host); 565 | if chunk.is_none() { continue; } 566 | let chunk = chunk.unwrap(); 567 | if self.bd > 16 { 568 | write_32s(&mut writer, &chunk.l, &chunk.r, chunk.len(), amplitude); 569 | } else { 570 | write_16s(&mut writer, &chunk.l, &chunk.r, chunk.len(), amplitude); 571 | } 572 | self.fb.set_time_to_next_block(); 573 | } 574 | } 575 | self.g.set_time(0); 576 | println!("{}Ok: done rendering.", GREEN); 577 | } 578 | } 579 | 580 | -------------------------------------------------------------------------------- /src/stream_workflow.rs: -------------------------------------------------------------------------------- 1 | use crate::state::*; 2 | 3 | use std::{ 4 | thread, 5 | sync::mpsc, 6 | time::{ Duration, Instant }, 7 | io::{ self }, 8 | }; 9 | 10 | use floww::*; 11 | use zen_colour::*; 12 | 13 | pub fn run_stream_workflow( 14 | proj_sr: usize, buffer_len: usize, state: State, device: sdl2::audio::AudioQueue 15 | ){ 16 | let (transmit_to_main, receive_in_main) = mpsc::channel(); 17 | 18 | launch_stream_thread(transmit_to_main); 19 | stream_partner(state, device, proj_sr, buffer_len, receive_in_main); 20 | } 21 | 22 | #[derive(PartialEq)] 23 | enum StreamThreadMsg{ 24 | Play, Feed(Vec), 25 | } 26 | 27 | fn launch_stream_thread(transmit_to_main: mpsc::Sender){ 28 | thread::spawn(move || { 29 | transmit_to_main.send(StreamThreadMsg::Play).unwrap(); 30 | loop{ 31 | if let Ok(res) = io::stdin().lock().decoded(){ 32 | transmit_to_main.send(StreamThreadMsg::Feed(res)).unwrap(); 33 | } else { 34 | println!("{}Error: could not decode std input.{}", RED, DEFAULT); 35 | std::process::exit(0x0100); 36 | } 37 | } 38 | }); 39 | } 40 | 41 | fn stream_partner( 42 | mut state: State, device: sdl2::audio::AudioQueue, proj_sr: usize, buffer_len: usize, 43 | receive_in_main: mpsc::Receiver 44 | ){ 45 | let mut playing = false; 46 | let mut since = Instant::now(); 47 | let mut millis_generated = 0f32; 48 | loop { 49 | if let Ok(rec) = receive_in_main.try_recv(){ 50 | macro_rules! check_loaded{ 51 | ($b:block) => { 52 | if !state.loaded{ 53 | println!("{}State not loaded!", RED); 54 | } else { 55 | $b; 56 | } 57 | } 58 | } 59 | match rec{ 60 | // StreamThreadMsg::Quit => { 61 | // break; 62 | // }, 63 | StreamThreadMsg::Feed(packets) => { 64 | check_loaded!({ 65 | state.fb.trim_streams(); 66 | let msgs = state.fb.append_streams(packets); 67 | let t = state.g.get_time(); 68 | state.fb.set_time(t); 69 | println!("MSGs: {:?}", msgs); 70 | }); 71 | }, 72 | StreamThreadMsg::Play => { 73 | check_loaded!({ 74 | playing = true; 75 | since = Instant::now(); 76 | millis_generated = 0.0; 77 | device.resume(); 78 | }); 79 | }, 80 | // StreamThreadMsg::Stop => { 81 | // playing = false; 82 | // device.pause(); 83 | // }, 84 | } 85 | } 86 | if playing{ 87 | if !state.loaded { 88 | playing = false; 89 | } else { 90 | let time_since = since.elapsed().as_millis() as f32; 91 | // render half second in advance to be played 92 | while time_since > millis_generated - 0.5 { 93 | let t = state.g.get_time(); 94 | state.fb.set_time(t); 95 | let chunk = state.g.render(&state.sb, &mut state.fb, &mut state.host); 96 | let chunk = chunk.unwrap(); 97 | let stream_data = chunk.clone().interleave(); 98 | let _ = device.queue_audio(&stream_data); 99 | millis_generated += buffer_len as f32 / proj_sr as f32 * 1000.0; 100 | state.fb.set_time_to_next_block(); 101 | } 102 | } 103 | } 104 | std::thread::sleep(Duration::from_millis(10)); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/synth.rs: -------------------------------------------------------------------------------- 1 | use crate::adsr::AdsrConf; 2 | 3 | use std::f32::consts::PI; 4 | 5 | pub struct OscConf{ 6 | pub volume: f32, 7 | pub param: f32, 8 | pub adsr: AdsrConf, 9 | } 10 | 11 | impl OscConf{ 12 | pub fn new(volume: f32, param: f32, adsr: AdsrConf) -> Self{ 13 | Self{ 14 | volume, 15 | param, 16 | adsr, 17 | } 18 | } 19 | } 20 | 21 | #[inline] 22 | pub fn square_sine_sample(t: f32, hz: f32, z: f32) -> f32{ 23 | (t * hz * 2.0 * PI).sin().max(-z).min(z) * (1.0 / z) 24 | } 25 | 26 | #[inline] 27 | pub fn topflat_sine_sample(t: f32, hz: f32, z: f32) -> f32{ 28 | ((t * hz * 2.0 * PI).sin().min(z) + ((1.0 - z) / 2.0)) * (2.0 / (1.0 + z)) 29 | } 30 | 31 | #[inline] 32 | pub fn triangle_sample(t: f32, hz: f32) -> f32{ 33 | 4.0 * ((t * hz) - ((t * hz) + 0.5).floor()).abs() - 1.0 34 | } 35 | 36 | // formula's i made for the square_sine and topflat_sine oscilators 37 | // https://graphtoy.com/?f1(x,t)=min(sin(x),0)*2+1&v1=false&f2(x,t)=max(sin(x),0)*2-1&v2=false&f3(x,t)=0.4&v3=false&f4(x,t)=(min(sin(x),f3(0))+((1-f3(0))/2))*(2/(1+f3(0)))&v4=true&f5(x,t)=(max(sin(x),-f3(0))-((1-f3(0))/2))*(2/(1+f3(0)))&v5=false&f6(x,t)=clamp(sin(x),-f3(0),f3(0))*(1/f3(0))&v6=true&grid=true&coords=0,0,4.205926793776712 38 | -------------------------------------------------------------------------------- /src/ui_workflow.rs: -------------------------------------------------------------------------------- 1 | use crate::state::*; 2 | 3 | use std::{ 4 | thread, 5 | sync::mpsc, 6 | time::{ Duration, Instant }, 7 | io::Cursor, 8 | }; 9 | 10 | use zen_colour::*; 11 | use term_basics_linux::{ input_field_simple, string_to_value }; 12 | use skim::prelude::*; 13 | 14 | pub fn run_ui_workflow( 15 | proj_sr: usize, buffer_len: usize, state: State, device: sdl2::audio::AudioQueue 16 | ){ 17 | let (transmit_to_ui, receive_in_ui) = mpsc::channel(); 18 | let (transmit_to_main, receive_in_main) = mpsc::channel(); 19 | 20 | launch_ui_thread(proj_sr, transmit_to_main, receive_in_ui); 21 | ui_partner(state, device, proj_sr, buffer_len, transmit_to_ui, receive_in_main); 22 | } 23 | 24 | #[derive(PartialEq)] 25 | enum UiThreadMsg{ 26 | None, Ready, Quit, Refresh, Render, Normalize, Play, Pause, Stop, Skip, Prev, Set(usize), 27 | Get, NormVals 28 | } 29 | 30 | fn launch_ui_thread( 31 | proj_sr: usize, transmit_to_main: mpsc::Sender, 32 | receive_in_ui: mpsc::Receiver 33 | ){ 34 | thread::spawn(move || { 35 | let options = SkimOptionsBuilder::default() 36 | .height(Some("8%")).build().unwrap(); 37 | let input = 38 | "quit\nrender\nrefresh\nnormalize\nplay\npause\nstop\n>skip\nskip" { UiThreadMsg::Skip } 58 | else if command == " = string_to_value(&raw); 63 | if let Some(float) = time{ 64 | if float >= 0.0{ 65 | let t = (float * proj_sr as f32) as usize; 66 | UiThreadMsg::Set(t) 67 | } else { 68 | println!("{}Error: time needs to be positive.", RED); 69 | UiThreadMsg::None 70 | } 71 | } else { 72 | println!("{}Error: could not parse time, did not set time.", RED); 73 | UiThreadMsg::None 74 | } 75 | } 76 | else if command == "get" { UiThreadMsg::Get } 77 | else { UiThreadMsg::None }; 78 | transmit_to_main.send(tmsg).unwrap(); 79 | } else { 80 | println!("{}TermDaw: command not found!", RED); 81 | continue; 82 | } 83 | for received in &receive_in_ui{ 84 | if received == UiThreadMsg::Ready{ 85 | break; 86 | } 87 | } 88 | } 89 | }); 90 | } 91 | 92 | fn ui_partner( 93 | mut state: State, device: sdl2::audio::AudioQueue, proj_sr: usize, buffer_len: usize, 94 | transmit_to_ui: mpsc::Sender, receive_in_main: mpsc::Receiver 95 | ){ 96 | let mut playing = false; 97 | let mut since = Instant::now(); 98 | let mut millis_generated = 0f32; 99 | loop { 100 | if let Ok(rec) = receive_in_main.try_recv(){ 101 | macro_rules! check_loaded{ 102 | ($b:block) => { 103 | if !state.loaded{ 104 | println!("{}State not loaded!", RED); 105 | } else { 106 | $b; 107 | } 108 | } 109 | } 110 | match rec{ 111 | UiThreadMsg::Quit => { 112 | break; 113 | }, 114 | UiThreadMsg::Refresh => { 115 | state.refresh(); 116 | playing = false; 117 | device.clear(); 118 | device.pause(); 119 | }, 120 | UiThreadMsg::Render => { 121 | check_loaded!({ 122 | device.clear(); 123 | device.pause(); 124 | playing = false; 125 | state.render(); 126 | }); 127 | }, 128 | UiThreadMsg::Normalize => { 129 | check_loaded!({ 130 | device.clear(); 131 | device.pause(); 132 | playing = false; 133 | state.scan_exact(); 134 | }); 135 | }, 136 | UiThreadMsg::Play => { 137 | check_loaded!({ 138 | playing = true; 139 | since = Instant::now(); 140 | millis_generated = 0.0; 141 | device.resume(); 142 | }); 143 | }, 144 | UiThreadMsg::Pause => { 145 | playing = false; 146 | device.pause(); 147 | }, 148 | UiThreadMsg::Stop => { 149 | check_loaded!({ 150 | playing = false; 151 | device.pause(); 152 | device.clear(); 153 | state.g.set_time(0); 154 | state.fb.set_time(0); 155 | }); 156 | }, 157 | UiThreadMsg::Skip => { 158 | check_loaded!({ 159 | device.clear(); 160 | let time = state.g.change_time(5 * proj_sr, true); 161 | state.fb.set_time(time); 162 | }); 163 | } 164 | UiThreadMsg::Prev => { 165 | check_loaded!({ 166 | device.clear(); 167 | let time = state.g.change_time(5 * proj_sr, false); 168 | state.fb.set_time(time); 169 | }); 170 | } 171 | UiThreadMsg::Set(time) => { 172 | check_loaded!({ 173 | device.clear(); 174 | state.g.set_time(time); 175 | state.fb.set_time(time); 176 | }); 177 | } 178 | UiThreadMsg::Get => { 179 | check_loaded!({ 180 | let t = state.g.get_time(); 181 | let tf = t as f32 / proj_sr as f32; 182 | println!("{s}Frame: {b}{t}{s}, Time: {b}{tf}", 183 | s = DEFAULT, b = BLUE, t = t, tf = tf); 184 | }); 185 | } 186 | UiThreadMsg::NormVals => { 187 | check_loaded!({ 188 | state.g.print_normalization_values(); 189 | }); 190 | } 191 | _ => {} 192 | } 193 | transmit_to_ui.send(UiThreadMsg::Ready).unwrap(); 194 | } 195 | if playing{ 196 | if !state.loaded { 197 | playing = false; 198 | } else { 199 | let time_since = since.elapsed().as_millis() as f32; 200 | // render half second in advance to be played 201 | while time_since > millis_generated - 0.5 { 202 | let chunk = state.g.render(&state.sb, &mut state.fb, &mut state.host); 203 | let chunk = chunk.unwrap(); 204 | let stream_data = chunk.clone().interleave(); 205 | let _ = device.queue_audio(&stream_data); 206 | millis_generated += buffer_len as f32 / proj_sr as f32 * 1000.0; 207 | state.fb.set_time_to_next_block(); 208 | } 209 | } 210 | } 211 | std::thread::sleep(Duration::from_millis(10)); 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /test_stream.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ../music-gen/target/debug/music-gen --mode stream | cargo run 3 | --------------------------------------------------------------------------------