├── .gitignore ├── .gitmodules ├── AUTHORS ├── COPYING ├── Makefile ├── README.md ├── audio.c ├── audio.h ├── common.c ├── common.h ├── config.h ├── dirt.c ├── file.c ├── file.h ├── jack.c ├── jack.h ├── jobqueue.c ├── jobqueue.h ├── pitch.c ├── pitch.h ├── segment.c ├── segment.h ├── server.c ├── server.h ├── thpool.c ├── thpool.h ├── windows └── dirt-pa.exe └── zmqserv.c /.gitignore: -------------------------------------------------------------------------------- 1 | *.d 2 | *.o 3 | dirt 4 | dirt-pa 5 | *.wav 6 | Makefile 7 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "samples"] 2 | path = samples 3 | url = https://github.com/tidalcycles/Dirt-Samples 4 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | (c) 2015 Alex McLean and contributors 2 | GPLv3.0 3 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC=gcc 2 | 3 | #CFLAGS += -O2 -march=armv6zk -mcpu=arm1176jzf-s -mfloat-abi=hard -mfpu=vfp -g -I/usr/local/include -I/opt/local/include -Wall -std=gnu99 -DDEBUG -DHACK -DFASTSIN -Wdouble-promotion 4 | CFLAGS += -O2 -g -I/usr/local/include -I/opt/local/include -Wall -std=gnu99 -DDEBUG -DHACK -DFASTSIN -MMD 5 | 6 | LDFLAGS += -g -lm -L/usr/local/lib -L/opt/local/lib -llo -lsndfile -lsamplerate -lpthread 7 | 8 | SOURCES=dirt.c common.c audio.c file.c server.c jobqueue.c thpool.c 9 | OBJECTS=$(SOURCES:.c=.o) 10 | DEPENDS=$(OBJECTS:.o=.d) 11 | 12 | dirt: CFLAGS += -DJACK -DSCALEPAN 13 | dirt: LDFLAGS += -ljack 14 | dirt-pa: LDFLAGS += -lportaudio 15 | dirt-pulse: CFLAGS += -DPULSE `pkg-config --cflags libpulse-simple` 16 | dirt-pulse: LDFLAGS += `pkg-config --libs libpulse-simple` -lpthread 17 | dirt-feedback: CFLAGS += -DFEEDBACK -DINPUT 18 | dirt-feedback: dirt 19 | 20 | clean: 21 | rm -f *.o *~ dirt dirt-analyse dirt-pa 22 | 23 | all: dirt 24 | 25 | dirt: $(OBJECTS) jack.o Makefile 26 | $(CC) $(OBJECTS) jack.o $(CFLAGS) $(LDFLAGS) -o $@ 27 | 28 | dirt-pa: $(OBJECTS) Makefile 29 | $(CC) $(OBJECTS) $(CFLAGS) $(LDFLAGS) -o $@ 30 | 31 | dirt-pulse: dirt.o common.o audio.o file.o server.o Makefile 32 | $(CC) dirt.o common.o audio.o file.o server.o $(CFLAGS) $(LDFLAGS) -o dirt-pulse 33 | 34 | test: test.c Makefile 35 | $(CC) test.c -llo -o test 36 | 37 | install: dirt 38 | install -d $(PREFIX)/bin 39 | install -m 0755 dirt $(PREFIX)/bin/dirt 40 | 41 | -include $(DEPENDS) 42 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | An unimpressive thingie for playing bits of samples with some level of accuracy. 2 | 3 | (c) Alex McLean and contributors, 2016 4 | Released under the GNU Public Licence version 3 5 | 6 | # Linux installation 7 | 8 | Here's how to install dirt under Debian, Ubuntu or a similar distribution: 9 | 10 | ~~~~sh 11 | sudo apt-get install build-essential libsndfile1-dev libsamplerate0-dev \ 12 | liblo-dev portaudio19-dev \ 13 | libjack-jackd2-dev qjackctl jackd git 14 | git clone --recursive https://github.com/tidalcycles/Dirt.git 15 | cd Dirt 16 | make clean; make 17 | ~~~~ 18 | 19 | ## Starting Dirt under Linux 20 | 21 | First of all, start the "jack" audio layer. The easier way to do this 22 | is with the "qjackctl" app, which you should find in your program 23 | menus under "Sound & Video" or similar. If you have trouble with 24 | qjackctl, you can also try starting jack directly from the 25 | commandline: 26 | 27 | ~~~~sh 28 | jackd -d alsa & 29 | ~~~~ 30 | 31 | If that doesn't work, you might well have something called 32 | "pulseaudio" in control of your sound. In that case, this should work: 33 | 34 | ~~~~sh 35 | /usr/bin/pasuspender -- jackd -d alsa & 36 | ~~~~ 37 | 38 | And finally you should be able to start dirt with this: 39 | 40 | ~~~~sh 41 | cd ~/Dirt 42 | ./dirt & 43 | ~~~~ 44 | 45 | If you have problems with jack, try enabling realtime audio, and 46 | adjusting the settings by installing and using the "qjackctl" 47 | software. Some more info can be found in the [Ubuntu Community page for JACK configuration](https://help.ubuntu.com/community/HowToJACKConfiguration) 48 | 49 | # MacOS installation 50 | 51 | Installing Dirt's dependencies on Mac OS X can be done via homebrew or 52 | MacPorts, but choose only one to avoid conflicts with duplicate system 53 | libraries. 54 | 55 | Unless otherwise specified, the below commands should be typed or 56 | pasted into a terminal window. 57 | 58 | ## Installing dependencies via Homebrew 59 | 60 | [Homebrew](http://brew.sh) is a package manager for OS X. It lives 61 | side by side with the native libraries and tools that ship with the 62 | operating system. 63 | 64 | To install homebrew: 65 | 66 | ~~~bash 67 | ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 68 | ~~~ 69 | 70 | Initialise homebrew: 71 | 72 | ~~~bash 73 | brew doctor 74 | ~~~ 75 | 76 | Install Dirt, a synth (well, more of a sampler) made to work with 77 | Tidal. A homebrew 'recipe' for dirt does exist, but that doesn't come 78 | with any sounds to play with, so for now it's probably easiest just 79 | download it all from github and compile it as follows. 80 | 81 | Install some libraries which the Dirt synth needs to compile: 82 | 83 | ~~~bash 84 | brew install liblo libsndfile libsamplerate 85 | ~~~ 86 | 87 | Install the 'jack audio connection kit' which Dirt also needs: 88 | 89 | ~~~bash 90 | brew install jack 91 | ~~~ 92 | 93 | *If Homebrew's installation of Jack fails with a `make` error, you can 94 | use the [JackOSX Installer](http://www.jackosx.com/download.html) 95 | instead. This will, however, add an additional step when installing 96 | Dirt (see below).* 97 | 98 | 99 | ### Alternative: Installing dependencies via Mac Ports 100 | 101 | [MacPorts](https://www.macports.org/) is another package manager for 102 | OS X. 103 | 104 | If you already installed dependencies via homebrew, skip ahead to build Dirt. 105 | Otherwise if you happen to already use MacPorts, here's a list of 106 | steps in order to get all dependencies: 107 | 108 | ~~~bash 109 | sudo port install liblo libsndfile libsamplerate 110 | ~~~ 111 | 112 | Download and install jack2 [Jack Download Page](http://jackaudio.org/downloads/). Jack 2 has better OS X integration [Jack Comparison](https://github.com/jackaudio/jackaudio.github.com/wiki/Q_difference_jack1_jack2). 113 | 114 | ## Building Dirt from source 115 | 116 | Get the source code for the Dirt synth: 117 | 118 | ~~~bash 119 | cd ~ 120 | git clone --recursive https://github.com/tidalcycles/Dirt.git 121 | ~~~ 122 | 123 | Compile dirt: 124 | 125 | ~~~bash 126 | cd ~/Dirt 127 | make clean; make 128 | ~~~ 129 | 130 | If Dirt fails to compile after using the JackOSX installer as above, 131 | you may need to add flags to the Makefile to specify the appropriate 132 | paths: 133 | 134 | ~~~make 135 | CFLAGS += -g -I/usr/local/include -Wall -O3 -std=gnu99 -DCHANNELS=2 136 | LDFLAGS += -lm -L/usr/local/lib -llo -lsndfile -lsamplerate -ljack 137 | ~~~ 138 | 139 | ### Homebrew users 140 | 141 | As MacPorts installs all libs on `/opt/local/` 142 | edit the Makefile to point the right direction of `libsndfile` and `libsamplerate` 143 | 144 | ~~~make 145 | CFLAGS += -g -I/opt/local/include -Wall -O3 -std=gnu99 146 | LDFLAGS += -lm -L/opt/local/lib -llo -lsndfile -lsamplerate 147 | ~~~ 148 | 149 | ## Starting Dirt under MacOS 150 | 151 | To start Dirt, back in a terminal window, first start jack: 152 | 153 | ~~~bash 154 | jackd -d coreaudio & 155 | ~~~ 156 | 157 | Or, if you downloaded Jack 2, then start the JackPilot at: 158 | /Applications/Jack/JackPilot.app 159 | 160 | Click __start__ button. 161 | 162 | Then start dirt: 163 | 164 | ~~~bash 165 | cd ~/Dirt 166 | ./dirt & 167 | ~~~ 168 | 169 | # Windows installation 170 | 171 | ## Cygwin 172 | 173 | First, install [Cygwin](https://www.cygwin.com). In Cygwin, make sure the 174 | following packages are installed: 175 | 176 | ~~~~ 177 | git 178 | gcc-core 179 | make 180 | gcc-g++ 181 | libsndfile 182 | libsndfile-devel 183 | libsamplerate 184 | libsamplerate-devel 185 | ~~~~ 186 | 187 | ## Portaudio 188 | 189 | Download Portaudio from http://www.portaudio.com. In Cygwin, Unpack 190 | the download with `tar fxvz`. After unpacking, from Cygwin, go to the directory 191 | where you unpacked Portaudio and then run: 192 | 193 | ~~~~bash 194 | ./configure && make && make install 195 | ~~~~ 196 | 197 | ## Liblo 198 | 199 | Download [Liblo](http://liblo.sourceforge.net). 200 | In Cygwin, unpack Liblo with `tar fxvz`, then in Cygwin go to the directory where you 201 | unpacked Liblo and then run: 202 | 203 | ~~~~bash 204 | ./configure && make && make install 205 | ~~~~ 206 | 207 | ## Dirt 208 | 209 | In Cygwin: 210 | 211 | ~~~~bash 212 | git clone --recursive http://github.com/tidalcycles/Dirt.git 213 | ~~~~ 214 | 215 | Then: 216 | 217 | ~~~~bash 218 | cd Dirt 219 | make dirt-pa 220 | ~~~~ 221 | 222 | Then you get a `dirt-pa.exe` that works. Maybe this even works on any 223 | windows system without having to compile. You'd need `cygwin1.dll` at 224 | least though. 225 | 226 | -------------------------------------------------------------------------------- /audio.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "common.h" 12 | #include "config.h" 13 | #include "thpool.h" 14 | 15 | #ifdef JACK 16 | #include "jack.h" 17 | #elif PULSE 18 | #include 19 | #include 20 | #include 21 | #else 22 | 23 | #include "portaudio.h" 24 | 25 | #ifdef __linux 26 | #include 27 | #endif 28 | 29 | PaStream *stream; 30 | 31 | #define PA_FRAMES_PER_BUFFER 1024 32 | 33 | #endif 34 | 35 | #include "audio.h" 36 | #include "server.h" 37 | #include "pitch.h" 38 | 39 | #define HALF_PI 1.5707963267948966f 40 | 41 | t_line* delays; 42 | float line_feedback_delay; 43 | 44 | pthread_mutex_t queue_loading_lock; 45 | pthread_mutex_t queue_waiting_lock; 46 | pthread_mutex_t mutex_sounds; 47 | 48 | t_sound *loading = NULL; 49 | t_sound *waiting = NULL; 50 | t_sound *playing = NULL; 51 | 52 | t_sound sounds[MAX_SOUNDS]; 53 | int playing_n = 0; 54 | 55 | double epochOffset = 0; 56 | float starttime = 0; 57 | 58 | #ifdef JACK 59 | jack_client_t *jack_client = NULL; 60 | #endif 61 | float compression_speed = -1; 62 | 63 | float delay_time = 0.1; 64 | float delay_feedback = 0.7; 65 | 66 | bool use_dirty_compressor = false; 67 | bool use_late_trigger = false; 68 | bool use_shape_gain_comp = false; 69 | 70 | thpool_t* read_file_pool; 71 | 72 | const char* sampleroot; 73 | 74 | void queue_add(t_sound **queue, t_sound *new); 75 | void init_sound(t_sound *sound); 76 | int queue_size(t_sound *queue); 77 | 78 | #ifdef SEND_RMS 79 | static t_rms rms[MAX_ORBIT*2]; 80 | #endif 81 | 82 | static int is_sample_loading(const char* samplename) { 83 | int result = 0; 84 | t_sound *p = loading; 85 | while (p != NULL) { 86 | if (strcmp(samplename, p->samplename) == 0) { 87 | result = 1; 88 | break; 89 | } 90 | p = p->next; 91 | } 92 | return(result); 93 | } 94 | 95 | static void mark_as_loading(t_sound* sound) { 96 | if (loading) { 97 | sound->prev = NULL; 98 | sound->next = loading; 99 | loading->prev = sound; 100 | } 101 | else { 102 | sound->prev = NULL; 103 | sound->next = NULL; 104 | } 105 | loading = sound; 106 | } 107 | 108 | static void unmark_as_loading(const char* samplename, t_sample *sample) { 109 | pthread_mutex_lock(&queue_loading_lock); 110 | t_sound *p = loading; 111 | while (p != NULL) { 112 | t_sound *next = p->next; 113 | if (strcmp(samplename, p->samplename) == 0) { 114 | if (p->prev == NULL) { 115 | loading = p->next; 116 | 117 | if (loading != NULL) { 118 | loading->prev = NULL; 119 | } 120 | } 121 | else { 122 | p->prev->next = p->next; 123 | if (p->next) { 124 | p->next->prev = p->prev; 125 | } 126 | } 127 | 128 | p->prev = NULL; 129 | p->next = NULL; 130 | if (sample) { 131 | p->sample = sample; 132 | init_sound(p); 133 | pthread_mutex_lock(&queue_waiting_lock); 134 | queue_add(&waiting, p); 135 | pthread_mutex_unlock(&queue_waiting_lock); 136 | } 137 | else { 138 | p->active = 0; 139 | } 140 | } 141 | p = next; 142 | } 143 | pthread_mutex_unlock(&queue_loading_lock); 144 | } 145 | 146 | static void reset_sound(t_sound* s); 147 | 148 | void *read_file_func(void* new) { 149 | t_sound* sound = new; 150 | t_sample *sample = file_get(sound->samplename, sampleroot); 151 | unmark_as_loading(sound->samplename, sample); 152 | return NULL; 153 | } 154 | 155 | int queue_size(t_sound *queue) { 156 | int result = 0; 157 | while (queue != NULL) { 158 | result++; 159 | queue = queue->next; 160 | if (result > 4096) { 161 | printf("whoops, big queue %d\n", result); 162 | break; 163 | } 164 | } 165 | return(result); 166 | } 167 | 168 | void queue_add(t_sound **queue, t_sound *new) { 169 | int added = 0; 170 | assert(new->next != new); 171 | assert(new->prev != new); 172 | if (*queue == NULL) { 173 | *queue = new; 174 | added++; 175 | } 176 | else { 177 | t_sound *tmp = *queue; 178 | assert(tmp->prev == NULL); 179 | 180 | int i =0; 181 | while (1) { 182 | if (tmp->startT > new->startT) { 183 | // insert in front of later event 184 | new->next = tmp; 185 | new->prev = tmp->prev; 186 | if (new->prev != NULL) { 187 | new->prev->next = new; 188 | } 189 | else { 190 | *queue = new; 191 | } 192 | tmp->prev = new; 193 | 194 | added++; 195 | break; 196 | } 197 | 198 | if (tmp->next == NULL) { 199 | // add to end of queue 200 | tmp->next = new; 201 | new->prev = tmp; 202 | added++; 203 | break; 204 | } 205 | ++i; 206 | tmp = tmp->next; 207 | } 208 | } 209 | 210 | assert(added == 1); 211 | } 212 | 213 | 214 | void queue_remove(t_sound **queue, t_sound *old) { 215 | // printf("played %d\n", old->played); 216 | if (old->prev == NULL) { 217 | *queue = old->next; 218 | if (*queue != NULL) { 219 | (*queue)->prev = NULL; 220 | } 221 | } 222 | else { 223 | old->prev->next = old->next; 224 | 225 | if (old->next) { 226 | old->next->prev = old->prev; 227 | } 228 | } 229 | old->active = 0; 230 | old->is_playing = 0; 231 | playing_n--; 232 | } 233 | 234 | const double coeff[5][11]= { 235 | { 3.11044e-06, 236 | 8.943665402, -36.83889529, 92.01697887, -154.337906, 181.6233289, 237 | -151.8651235, 89.09614114, -35.10298511, 8.388101016, -0.923313471 238 | }, 239 | {4.36215e-06, 240 | 8.90438318, -36.55179099, 91.05750846, -152.422234, 179.1170248, 241 | -149.6496211,87.78352223, -34.60687431, 8.282228154, -0.914150747 242 | }, 243 | { 3.33819e-06, 244 | 8.893102966, -36.49532826, 90.96543286, -152.4545478, 179.4835618, 245 | -150.315433, 88.43409371, -34.98612086, 8.407803364, -0.932568035 246 | }, 247 | {1.13572e-06, 248 | 8.994734087, -37.2084849, 93.22900521, -156.6929844, 184.596544, 249 | -154.3755513, 90.49663749, -35.58964535, 8.478996281, -0.929252233 250 | }, 251 | {4.09431e-07, 252 | 8.997322763, -37.20218544, 93.11385476, -156.2530937, 183.7080141, 253 | -153.2631681, 89.59539726, -35.12454591, 8.338655623, -0.910251753 254 | } 255 | }; 256 | 257 | float formant_filter(float in, t_sound *sound, int channel) { 258 | float res = 259 | (float) ( coeff[sound->formant_vowelnum][0] * in + 260 | coeff[sound->formant_vowelnum][1] * sound->formant_history[channel][0] + 261 | coeff[sound->formant_vowelnum][2] * sound->formant_history[channel][1] + 262 | coeff[sound->formant_vowelnum][3] * sound->formant_history[channel][2] + 263 | coeff[sound->formant_vowelnum][4] * sound->formant_history[channel][3] + 264 | coeff[sound->formant_vowelnum][5] * sound->formant_history[channel][4] + 265 | coeff[sound->formant_vowelnum][6] * sound->formant_history[channel][5] + 266 | coeff[sound->formant_vowelnum][7] * sound->formant_history[channel][6] + 267 | coeff[sound->formant_vowelnum][8] * sound->formant_history[channel][7] + 268 | coeff[sound->formant_vowelnum][9] * sound->formant_history[channel][8] + 269 | coeff[sound->formant_vowelnum][10] * sound->formant_history[channel][9] 270 | ); 271 | 272 | sound->formant_history[channel][9] = sound->formant_history[channel][8]; 273 | sound->formant_history[channel][8] = sound->formant_history[channel][7]; 274 | sound->formant_history[channel][7] = sound->formant_history[channel][6]; 275 | sound->formant_history[channel][6] = sound->formant_history[channel][5]; 276 | sound->formant_history[channel][5] = sound->formant_history[channel][4]; 277 | sound->formant_history[channel][4] = sound->formant_history[channel][3]; 278 | sound->formant_history[channel][3] = sound->formant_history[channel][2]; 279 | sound->formant_history[channel][2] = sound->formant_history[channel][1]; 280 | sound->formant_history[channel][1] = sound->formant_history[channel][0]; 281 | sound->formant_history[channel][0] = (float) res; 282 | return res; 283 | } 284 | 285 | void init_formant_history (t_sound *sound) { 286 | // If uninitialized, create arrays 287 | // TODO alloc - initialise at startup ? 288 | if (!sound->formant_history) { 289 | bool failed = false; 290 | 291 | sound->formant_history = malloc(g_num_channels * sizeof(double*)); 292 | if (!sound->formant_history) failed = true; 293 | 294 | for (int c = 0; c < g_num_channels; c++) { 295 | sound->formant_history[c] = malloc(10 * sizeof(double)); 296 | if (!sound->formant_history[c]) failed = true; 297 | } 298 | 299 | if (failed) { 300 | fprintf(stderr, "no memory to allocate `formant_history' array\n"); 301 | exit(1); 302 | } 303 | } 304 | 305 | // Clean history for each channel 306 | for (int c = 0; c < g_num_channels; c++) { 307 | memset(sound->formant_history[c], 0, 10 * sizeof(double)); 308 | } 309 | } 310 | 311 | void free_formant_history (t_sound *sound) { 312 | if (sound->formant_history) { 313 | for (int c = 0; c < g_num_channels; c++) { 314 | double* fh = sound->formant_history[c]; 315 | if (fh) free(fh); 316 | } 317 | free(sound->formant_history); 318 | } 319 | sound->formant_history = NULL; 320 | } 321 | 322 | void init_crs(t_sound *sound) { 323 | // TODO alloc - init at startup ? 324 | if (!sound->coarsef) { 325 | sound->coarsef = malloc(g_num_channels * sizeof(t_crs)); 326 | if (!sound->coarsef) { 327 | fprintf(stderr, "no memory to allocate crs struct\n"); 328 | exit(1); 329 | } 330 | } 331 | memset(sound->coarsef, 0, g_num_channels * sizeof(t_crs)); 332 | } 333 | 334 | void init_vcf (t_sound *sound) { 335 | if (!sound->vcf) { 336 | sound->vcf = malloc(g_num_channels * sizeof(t_vcf)); 337 | if (!sound->vcf) { 338 | fprintf(stderr, "no memory to allocate vcf struct\n"); 339 | exit(1); 340 | } 341 | } 342 | 343 | memset(sound->vcf, 0, g_num_channels * sizeof(t_vcf)); 344 | 345 | for (int channel = 0; channel < g_num_channels; ++channel) { 346 | t_vcf *vcf = &(sound->vcf[channel]); 347 | vcf->f = 2 * sound->cutoff; 348 | vcf->k = 3.6f * vcf->f - 1.6f * vcf->f * vcf->f -1; 349 | vcf->p = (vcf->k+1) * 0.5f; 350 | vcf->scale = exp((1-vcf->p)*1.386249f); 351 | vcf->r = sound->resonance * vcf->scale; 352 | vcf->y1 = 0; 353 | vcf->y2 = 0; 354 | vcf->y3 = 0; 355 | vcf->y4 = 0; 356 | vcf->oldx = 0; 357 | vcf->oldy1 = 0; 358 | vcf->oldy2 = 0; 359 | vcf->oldy3 = 0; 360 | } 361 | } 362 | 363 | void init_hpf (t_sound *sound) { 364 | if (!sound->hpf) { 365 | sound->hpf = malloc(g_num_channels * sizeof(t_vcf)); 366 | if (!sound->hpf) { 367 | fprintf(stderr, "no memory to allocate hpf struct\n"); 368 | exit(1); 369 | } 370 | } 371 | 372 | for (int channel = 0; channel < g_num_channels; ++channel) { 373 | t_vcf *vcf = &(sound->hpf[channel]); 374 | vcf->f = 2 * sound->hcutoff; 375 | vcf->k = 3.6f * vcf->f - 1.6f * vcf->f * vcf->f -1; 376 | vcf->p = (vcf->k+1) * 0.5f; 377 | vcf->scale = exp((1-vcf->p)*1.386249f); 378 | vcf->r = sound->hresonance * vcf->scale; 379 | vcf->y1 = 0; 380 | vcf->y2 = 0; 381 | vcf->y3 = 0; 382 | vcf->y4 = 0; 383 | vcf->oldx = 0; 384 | vcf->oldy1 = 0; 385 | vcf->oldy2 = 0; 386 | vcf->oldy3 = 0; 387 | } 388 | } 389 | 390 | void init_bpf (t_sound *sound) { 391 | if (!sound->bpf) { 392 | sound->bpf = malloc(g_num_channels * sizeof(t_vcf)); 393 | if (!sound->bpf) { 394 | fprintf(stderr, "no memory to allocate bpf struct\n"); 395 | exit(1); 396 | } 397 | } 398 | 399 | // I've changed the meaning of some of these a bit 400 | for (int channel = 0; channel < g_num_channels; ++channel) { 401 | t_vcf *vcf = &(sound->bpf[channel]); 402 | vcf->f = fabsf(sound->bandf); 403 | vcf->r = sound->bandq; 404 | vcf->k = vcf->f / vcf->r; 405 | vcf->p = 2.0f - vcf->f * vcf->f; 406 | vcf->scale = 1.0f / (1.0f + vcf->k); 407 | vcf->y1 = 0; 408 | vcf->y2 = 0; 409 | vcf->y3 = 0; 410 | vcf->y4 = 0; 411 | vcf->oldx = 0; 412 | vcf->oldy1 = 0; 413 | vcf->oldy2 = 0; 414 | vcf->oldy3 = 0; 415 | } 416 | } 417 | 418 | void free_vcf (t_sound *sound) { 419 | if (sound->vcf) free(sound->vcf); 420 | } 421 | 422 | void free_hpf (t_sound *sound) { 423 | if (sound->hpf) free(sound->hpf); 424 | } 425 | 426 | void free_bpf (t_sound *sound) { 427 | if (sound->bpf) free(sound->bpf); 428 | } 429 | 430 | float effect_coarse(float in, t_sound *sound, int channel) { 431 | t_crs *crs = &(sound->coarsef[channel]); 432 | 433 | (crs->index)++; 434 | if (sound->coarse > 0) { 435 | if (crs->index == sound->coarse) { 436 | crs->index = 0; 437 | crs->last = in; 438 | } 439 | } 440 | if (sound->coarse < 0) { 441 | crs->sum += in / (float) -(sound->coarse); 442 | if (crs->index == -(sound->coarse)) { 443 | crs->last = crs->sum; 444 | crs->index = 0; 445 | crs->sum = 0; 446 | } 447 | } 448 | return crs->last; 449 | } 450 | 451 | #ifdef FASTPOW 452 | float fastPow(float a, float b) { 453 | union { 454 | float d; 455 | int x[2]; 456 | } u = { a }; 457 | u.x[1] = (int)(b * (u.x[1] - 1072632447) + 1072632447); 458 | u.x[0] = 0; 459 | return u.d; 460 | } 461 | #endif 462 | 463 | #ifdef FASTPOW 464 | #define myPow (float) fastPow 465 | #else 466 | #define myPow (float) powf 467 | #endif 468 | 469 | float effect_vcf(float in, t_sound *sound, int channel) { 470 | t_vcf *vcf = &(sound->vcf[channel]); 471 | vcf->x = in - vcf->r * vcf->y4; 472 | 473 | float xp = vcf->x * vcf->p; 474 | float y1p = vcf->y1 * vcf->p; 475 | float y2p = vcf->y2 * vcf->p; 476 | float y3p = vcf->y3 * vcf->p; 477 | 478 | vcf->y1 = xp + vcf->oldx - vcf->k * vcf->y1; 479 | vcf->y2 = y1p + vcf->oldy1 - vcf->k * vcf->y2; 480 | vcf->y3 = y2p + vcf->oldy2 - vcf->k * vcf->y3; 481 | vcf->y4 = y3p + vcf->oldy3 - vcf->k * vcf->y4; 482 | 483 | vcf->y4 = vcf->y4 - (vcf->y4 * vcf->y4 * vcf->y4) / 6; 484 | 485 | vcf->oldx = xp; 486 | vcf->oldy1 = y1p; 487 | vcf->oldy2 = y2p; 488 | vcf->oldy3 = y3p; 489 | 490 | return vcf->y4; 491 | } 492 | 493 | float effect_hpf(float in, t_sound *sound, int channel) { 494 | t_vcf *vcf = &(sound->hpf[channel]); 495 | vcf->x = in - vcf->r * vcf->y4; 496 | 497 | vcf->y1 = vcf->x * vcf->p + vcf->oldx * vcf->p - vcf->k * vcf->y1; 498 | vcf->y2 = vcf->y1 * vcf->p + vcf->oldy1 * vcf->p - vcf->k * vcf->y2; 499 | vcf->y3 = vcf->y2 * vcf->p + vcf->oldy2 * vcf->p - vcf->k * vcf->y3; 500 | vcf->y4 = vcf->y3 * vcf->p + vcf->oldy3 * vcf->p - vcf->k * vcf->y4; 501 | 502 | vcf->y4 = vcf->y4 - (vcf->y4 * vcf->y4 * vcf->y4) / 6; 503 | 504 | vcf->oldx = vcf->x; 505 | vcf->oldy1 = vcf->y1; 506 | vcf->oldy2 = vcf->y2; 507 | vcf->oldy3 = vcf->y3; 508 | 509 | return (in - vcf->y4); 510 | } 511 | 512 | float effect_bpf(float in, t_sound *sound, int channel) { 513 | t_vcf *vcf = &(sound->bpf[channel]); 514 | vcf->x = in; 515 | 516 | vcf->y3 = vcf->p * vcf->y2 - vcf->y1 + vcf->k * (vcf->x - vcf->oldx + 517 | vcf->y2); 518 | vcf->y3 = vcf->scale * vcf->y3; 519 | 520 | vcf->oldx = vcf->x; 521 | vcf->y1 = vcf->y2; 522 | vcf->y2 = vcf->y3; 523 | return (vcf->y3); 524 | } 525 | 526 | /**/ 527 | 528 | /**/ 529 | 530 | void add_delay(t_line *line, float sample, float delay, float feedback) { 531 | int point = (line->point + (int) ( delay * MAXLINE )) % MAXLINE; 532 | 533 | //printf("'feedback': %f\n", feedback); 534 | line->samples[point] += (sample * feedback); 535 | } 536 | 537 | /**/ 538 | 539 | float shift_delay(t_line *line) { 540 | float result = line->samples[line->point]; 541 | line->samples[line->point] = 0; 542 | line->point = (line->point + 1) % MAXLINE; 543 | return(result); 544 | } 545 | 546 | /**/ 547 | 548 | extern int audio_play(t_sound* sound) { 549 | t_sample *sample = NULL; 550 | 551 | sample = file_get_from_cache(sound->samplename); 552 | 553 | if (sample != NULL) { 554 | sound->sample = sample; 555 | 556 | init_sound(sound); 557 | sound->prev = NULL; 558 | sound->next = NULL; 559 | pthread_mutex_lock(&queue_waiting_lock); 560 | queue_add(&waiting, sound); 561 | pthread_mutex_unlock(&queue_waiting_lock); 562 | } 563 | else { 564 | pthread_mutex_lock(&queue_loading_lock); 565 | if (!is_sample_loading(sound->samplename)) { 566 | if (!thpool_add_job(read_file_pool, read_file_func, (void*) sound)) { 567 | fprintf(stderr, "audio_play: Could not add file reading job for '%s'\n", sound->samplename); 568 | } 569 | } 570 | mark_as_loading(sound); 571 | pthread_mutex_unlock(&queue_loading_lock); 572 | } 573 | 574 | return(1); 575 | 576 | } 577 | 578 | void init_sound(t_sound *sound) { 579 | 580 | float start_pc = sound->start; 581 | float end_pc = sound->end; 582 | t_sample *sample = sound->sample; 583 | 584 | // switch to frames not percent.. 585 | sound->start = 0; 586 | sound->end = sample->info->frames; 587 | sound->items = sample->items; 588 | sound->channels = sample->info->channels; 589 | 590 | sound->active = 1; 591 | 592 | if (sound->delay > 1) { 593 | sound->delay = 1; 594 | } 595 | 596 | if (sound->delaytime > 1) { 597 | sound->delaytime = 1; 598 | } 599 | 600 | if (sound->delayfeedback >= 1) { 601 | sound->delayfeedback = 0.9999; 602 | } 603 | 604 | #ifdef JACK 605 | sound->startT = (sound->when - epochOffset) * 1000000; 606 | # else 607 | sound->startT = sound->when - epochOffset; 608 | #endif 609 | 610 | 611 | if (sound->unit == 's') { // unit = "sec" 612 | sound->accelerate = sound->accelerate / sound->speed; // change rate by 1 per specified duration 613 | sound->speed = sound->sample->info->frames / sound->speed / g_samplerate; 614 | } 615 | else if (sound->unit == 'c') { // unit = "cps" 616 | sound->accelerate = sound->accelerate * sound->speed * sound->cps; // change rate by 1 per cycle 617 | sound->speed = sound->sample->info->frames * sound->speed * sound->cps / g_samplerate; 618 | } 619 | // otherwise, unit is rate/ratio, 620 | // i.e. 2 = twice as fast, -1 = normal but backwards 621 | 622 | sound->next = NULL; 623 | sound->prev = NULL; 624 | sound->reverse = sound->speed < 0; 625 | sound->speed = fabsf(sound->speed); 626 | 627 | if (sound->channels == 2 && g_num_channels == 2 && sound->pan == 0.5f) { 628 | sound->pan = 0; 629 | } 630 | else { 631 | sound->mono = 1; 632 | } 633 | #ifdef FAKECHANNELS 634 | sound->pan *= (float) g_num_channels / FAKECHANNELS; 635 | #endif 636 | #ifdef SCALEPAN 637 | if (g_num_channels > 2) { 638 | sound->pan *= (float) g_num_channels; 639 | } 640 | #endif 641 | init_formant_history(sound); 642 | 643 | // if (sound->shape != 0) { 644 | // float tmp = sound->shape; 645 | // tmp = fabs(tmp); 646 | // if (tmp > 0.99) { 647 | // tmp = 0.99; 648 | // } 649 | // sound->shape = 1; 650 | // sound->shape_k = (2.0f * tmp) / (1.0f - tmp); 651 | // } 652 | 653 | if (sound->crush != 0) { 654 | float tmp = sound->crush; 655 | sound->crush = (tmp > 0) ? 1 : -1; 656 | sound->crush_bits = fabsf(tmp); 657 | } 658 | 659 | init_crs(sound); 660 | 661 | if (start_pc < 0) { 662 | start_pc = 0; 663 | sound->cut_continue = 1; 664 | } 665 | 666 | init_vcf(sound); 667 | init_hpf(sound); 668 | init_bpf(sound); 669 | 670 | if (sound->delaytime >= 0) { 671 | delay_time = sound->delaytime; 672 | } 673 | if (sound->delayfeedback >= 0) { 674 | delay_feedback = sound->delayfeedback; 675 | } 676 | 677 | if (sound->reverse) { 678 | float tmp = start_pc; 679 | start_pc = 1 - end_pc; 680 | end_pc = 1 - tmp; 681 | } 682 | 683 | //printf("frames: %f\n", new->end); 684 | if (start_pc > 0 && start_pc <= 1) { 685 | sound->start = start_pc * sound->end; 686 | } 687 | 688 | if (end_pc > 0 && end_pc < 1) { 689 | sound->end *= end_pc; 690 | } 691 | sound->position = sound->start; 692 | sound->playtime = 0.0; 693 | } 694 | 695 | 696 | t_sound *queue_next(t_sound **queue, sampletime_t now) { 697 | t_sound *result = NULL; 698 | // printf("queue_next - waiting sz %d / %d\n", queue_size(*queue), queue_size(waiting)); 699 | //printf("%f vs %f\n", *queue == NULL ? 0 : (*queue)->startT, now); 700 | if (*queue != NULL && (*queue)->startT <= now) { 701 | result = *queue; 702 | *queue = (*queue)->next; 703 | if ((*queue) != NULL) { 704 | (*queue)->prev = NULL; 705 | } 706 | } 707 | return(result); 708 | } 709 | 710 | void cut(t_sound *s) { 711 | t_sound *p = NULL; 712 | p = playing; 713 | 714 | int group = s->cutgroup; 715 | 716 | if (group != 0) { 717 | while (p != NULL) { 718 | // If group is less than 0, only cut playback of the same sample 719 | if (p->cutgroup == group && (group > 0 || p->sample == s->sample)) { 720 | // schedule this sound to end in ROUNDOFF samples time, so we 721 | // don't get a click 722 | float newend = p->position + ROUNDOFF; 723 | // unless it's dying soon anyway.. 724 | if (newend < p->end) { 725 | p->end = newend; 726 | // cut_continue means start the next where the prev is leaving off 727 | if (s->cut_continue > 0 && p->position < s->end) { 728 | s->start = p->position; 729 | s->position = p->position; 730 | s->cut_continue = 0; 731 | } 732 | } 733 | // cut should also kill any looping 734 | p->sample_loop = 0; 735 | } 736 | p = p->next; 737 | } 738 | } 739 | } 740 | 741 | void dequeue(sampletime_t now) { 742 | t_sound *p; 743 | pthread_mutex_lock(&queue_waiting_lock); 744 | assert(waiting == NULL || waiting->next != waiting); 745 | 746 | while ((p = queue_next(&waiting, now)) != NULL) { 747 | int s = queue_size(playing); 748 | cut(p); 749 | p->prev = NULL; 750 | p->next = playing; 751 | 752 | p->is_playing = 1; 753 | playing_n++; 754 | 755 | if (playing != NULL) { 756 | playing->prev = p; 757 | } 758 | playing = p; 759 | #ifdef DEBUG 760 | assert(s == (queue_size(playing) - 1)); 761 | #endif 762 | 763 | //printf("done.\n"); 764 | } 765 | pthread_mutex_unlock(&queue_waiting_lock); 766 | } 767 | 768 | float compress(float in) { 769 | static float env = 0; 770 | env += (float) 50 / g_samplerate; 771 | if (fabs(in * env) > 1) { 772 | env = env / (float) fabs(in * env); 773 | } 774 | return(env); 775 | } 776 | 777 | float compressdave(float in) { 778 | static float threshold = 0.5; 779 | static float env = 0; 780 | float result = in; 781 | // square input (to abs and make logarithmic) 782 | float t=in*in; 783 | 784 | // blend to create simple envelope follower 785 | env = env*(1-compression_speed) + t*compression_speed; 786 | 787 | // if we are over the threshold 788 | if (env > threshold) { 789 | // calculate the gain related to amount over thresh 790 | result *= 1.0f / (1.0f+(env - threshold)); 791 | } 792 | return(result); 793 | } 794 | 795 | /**/ 796 | 797 | void playback(float **buffers, int frame, sampletime_t now) { 798 | int channel, isgn; 799 | t_sound *p = playing; 800 | 801 | #ifdef SEND_RMS 802 | for (int i = 0; i < (MAX_ORBIT*2); ++i) { 803 | rms[i].sum = 0; 804 | rms[i].n = (rms[i].n + 1) % RMS_SZ; 805 | } 806 | #endif 807 | 808 | for (channel = 0; channel < g_num_channels; ++channel) { 809 | buffers[channel][frame] = 0; 810 | } 811 | 812 | while (p != NULL) { 813 | int channels; 814 | t_sound *tmp; 815 | 816 | if (p->startT > now) { 817 | p->checks++; 818 | p = p->next; 819 | continue; 820 | } 821 | if ((!p->started) && p->checks == 0 && p->startT < now) { 822 | /* printf("started late by %f frames (%d checks)\n", 823 | now - p->startT, p->checks 824 | );*/ 825 | p->started = 1; 826 | } 827 | //printf("playing %s\n", p->samplename); 828 | channels = p->channels; 829 | 830 | //printf("channels: %d\n", channels); 831 | for (channel = 0; channel < channels; ++channel) { 832 | float roundoff = 1; 833 | float value; 834 | 835 | value = p->items[(channels * (p->reverse ? (p->sample->info->frames - (int) p->position) : (int) p->position)) + channel]; 836 | 837 | int pos = ((int) p->position) + 1; 838 | if (pos < p->end) { 839 | float next = 840 | p->items[(channels * (p->reverse ? p->sample->info->frames - pos : pos)) 841 | + channel 842 | ]; 843 | float tween_amount = (p->position - (int) p->position); 844 | 845 | /* linear interpolation */ 846 | value += (next - value) * tween_amount; 847 | } 848 | 849 | if (p->formant_vowelnum >= 0) { 850 | value = formant_filter(value, p, 0); 851 | } 852 | 853 | // why 44000 (or 44100)? init_vcf divides by samplerate.. 854 | if (p->resonance > 0 && p->resonance < 1 855 | && p->cutoff > 0 && p->cutoff < 1) { 856 | value = effect_vcf(value, p, channel); 857 | } 858 | if (p->hresonance > 0 && p->hresonance < 1 859 | && p->hcutoff > 0 && p->hcutoff < 1) { 860 | value = effect_hpf(value, p, channel); 861 | } 862 | if (p->bandf > 0 && p->bandf < 1 && p->bandq > 0) { 863 | value = effect_bpf(value, p, channel); 864 | } else if (p->bandf < 0 && p->bandf > -1 && p->bandq > 0) { 865 | value = value - effect_bpf(value, p, channel); 866 | } 867 | 868 | if ((p->end - p->position) < ROUNDOFF) { 869 | // TODO what if end < ROUNDOFF?) 870 | //printf("roundoff: %f\n", (p->end - pos) / (float) ROUNDOFF); 871 | roundoff = (p->end - p->position) / (float) ROUNDOFF; 872 | //printf("end roundoff: %f (%f)\n", roundoff, p->end - p->position); 873 | } 874 | else { 875 | if ((p->position - p->start) < ROUNDOFF) { 876 | roundoff = (p->position - p->start) / (float) ROUNDOFF; 877 | //printf("start roundoff: %f (%f / %d)\n", roundoff, p->position - p->start, ROUNDOFF); 878 | } 879 | } 880 | 881 | if (p->coarse != 0) { 882 | value = effect_coarse(value, p, channel); 883 | } 884 | 885 | if (p->shape) { 886 | value = (1+p->shape_k)*value/(1+p->shape_k*(float) fabs(value)); 887 | // gain compensation, fine-tuned by ear 888 | if (use_shape_gain_comp) { 889 | float gcomp = 1.0f - (0.15f * p->shape_k / (p->shape_k + 2.0f)); 890 | value *= gcomp * gcomp; 891 | } 892 | } 893 | if (p->crush > 0) { 894 | //value = (1.0 + log(fabs(value)) / 16.63553) * (value / fabs(value)); 895 | float tmp = myPow(2,p->crush_bits-1); 896 | value = (float) trunc(tmp * value) / tmp; 897 | //value = exp( (fabs(value) - 1.0) * 16.63553 ) * (value / fabs(value)); 898 | } else if (p->crush < 0) { 899 | isgn = (value >= 0) ? 1 : -1; 900 | value = isgn * myPow(fabsf(value), 0.125); 901 | value = (float) trunc(((float) myPow(2,p->crush_bits-1) * value)) / ((float) myPow(2,p->crush_bits-1)); 902 | value = isgn * myPow(value, 8.0); 903 | } 904 | 905 | 906 | value *= p->gain; 907 | // envelope 908 | float env = 1.0; 909 | if (p->attack >= 0 && p->release >= 0) { 910 | if (p->playtime < p->attack) { 911 | env = 1.0523957 - 1.0523958*exp(-3.0 * p->playtime/p->attack); 912 | } else if (p->playtime > (p->attack + p->hold + p->release)) { 913 | env = 0.0; 914 | } else if (p->playtime > (p->attack + p->hold)) { 915 | env = 1.0523957 * 916 | exp(-3.0 * (p->playtime - p->attack - p->hold) / p->release) 917 | - 0.0523957; 918 | } 919 | } 920 | value *= env; 921 | 922 | value *= roundoff; 923 | 924 | float c = (float) channel + p->pan; 925 | float d = c - (float) floor(c); 926 | int channel_a = ((int) c) % g_num_channels; 927 | int channel_b = ((int) c + 1) % g_num_channels; 928 | 929 | if (channel_a < 0) { 930 | channel_a += g_num_channels; 931 | } 932 | if (channel_b < 0) { 933 | channel_b += g_num_channels; 934 | } 935 | 936 | // equal power panning 937 | // PERF - 8.4% of time? 938 | float tmpa, tmpb; 939 | // optimisations for middle, hard left + hard right 940 | if (d == 0.5f) { 941 | tmpa = tmpb = value * 0.7071067811f; 942 | } 943 | else if (d == 0) { 944 | tmpa = value; 945 | tmpb = 0; 946 | } 947 | else if (d == 1) { 948 | tmpa = 0; 949 | tmpb = value; 950 | } 951 | else { 952 | tmpa = value * (float) cos(HALF_PI * d); 953 | tmpb = value * (float) sin(HALF_PI * d); 954 | } 955 | 956 | buffers[channel_a][frame] += tmpa; 957 | buffers[channel_b][frame] += tmpb; 958 | 959 | #ifdef SEND_RMS 960 | rms[p->orbit*2 + channel_a].sum += tmpa; 961 | rms[p->orbit*2 + channel_b].sum += tmpb; 962 | #endif 963 | 964 | if (p->delay > 0) { 965 | add_delay(&delays[channel_a], tmpa, delay_time, p->delay); 966 | add_delay(&delays[channel_b], tmpb, delay_time, p->delay); 967 | } 968 | 969 | if (p->mono) { 970 | break; 971 | } 972 | } 973 | 974 | if (p->accelerate != 0) { 975 | // ->startFrame ->end ->position 976 | p->speed += p->accelerate/g_samplerate; 977 | } 978 | p->position += p->speed; 979 | p->playtime += 1.0 / g_samplerate; 980 | 981 | p->played++; 982 | //printf("position: %d of %d\n", p->position, playing->end); 983 | /* remove dead sounds */ 984 | tmp = p; 985 | p = p->next; 986 | if (tmp->position >= tmp->end || tmp->position < tmp->start) { 987 | if (--(tmp->sample_loop) > 0) { 988 | tmp->position = tmp->start; 989 | } else { 990 | queue_remove(&playing, tmp); 991 | } 992 | } 993 | } 994 | 995 | for (channel = 0; channel < g_num_channels; ++channel) { 996 | float tmp = shift_delay(&delays[channel]); 997 | if (delay_feedback > 0 && tmp != 0) { 998 | add_delay(&delays[channel], tmp, delay_time, delay_feedback); 999 | } 1000 | buffers[channel][frame] += tmp; 1001 | } 1002 | 1003 | if (use_dirty_compressor) { 1004 | float max = 0; 1005 | 1006 | for (channel = 0; channel < g_num_channels; ++channel) { 1007 | if (fabsf(buffers[channel][frame]) > max) { 1008 | max = buffers[channel][frame]; 1009 | } 1010 | } 1011 | float factor = compress(max); 1012 | for (channel = 0; channel < g_num_channels; ++channel) { 1013 | buffers[channel][frame] *= factor * g_gain/5.0f; 1014 | } 1015 | } else { 1016 | for (channel = 0; channel < g_num_channels; ++channel) { 1017 | buffers[channel][frame] *= g_gain; 1018 | } 1019 | } 1020 | #ifdef SEND_RMS 1021 | for (int i = 0; i < MAX_ORBIT*2; ++i) { 1022 | rms[i].sum_of_squares -= rms[i].squares[rms[i].n]; 1023 | 1024 | // this happens sometimes. could be a floating point error? 1025 | if (rms[i].sum_of_squares < 0) { 1026 | rms[i].sum_of_squares = 0; 1027 | } 1028 | 1029 | if (rms[i].sum == 0) { 1030 | rms[i].squares[rms[i].n] = 0; 1031 | } 1032 | else { 1033 | float sqrd = rms[i].sum * rms[i].sum; 1034 | rms[i].squares[rms[i].n] = sqrd; 1035 | rms[i].sum_of_squares += sqrd; 1036 | } 1037 | } 1038 | #endif 1039 | } 1040 | 1041 | 1042 | #ifdef JACK 1043 | extern int jack_callback(int frames, float *input, float **outputs) { 1044 | sampletime_t now; 1045 | 1046 | struct timeval tv; 1047 | gettimeofday(&tv, NULL); 1048 | epochOffset = ((double) tv.tv_sec + ((double) tv.tv_usec / 1000000.0)) 1049 | - ((double) jack_get_time() / 1000000.0); 1050 | //printf("jack time: %d tv_sec %d epochOffset: %f\n", jack_get_time(), tv.tv_sec, epochOffset); 1051 | 1052 | now = jack_last_frame_time(jack_client); 1053 | 1054 | for (int i=0; i < frames; ++i) { 1055 | jack_time_t nowt = jack_frames_to_time(jack_client, now + i); 1056 | playback(outputs, i, nowt); 1057 | 1058 | dequeue(nowt); 1059 | } 1060 | return(0); 1061 | } 1062 | #elif PULSE 1063 | 1064 | void run_pulse() { 1065 | #define FRAMES 64 1066 | struct timeval tv; 1067 | double samplelength = (((double) 1)/((double) g_samplerate)); 1068 | 1069 | float *buf[g_num_channels]; 1070 | for (int i = 0 ; i < g_num_channels; ++i) { 1071 | buf[i] = (float*) malloc(sizeof(float)*FRAMES); 1072 | } 1073 | float interlaced[g_num_channels*FRAMES]; 1074 | 1075 | pa_sample_spec ss; 1076 | ss.format = PA_SAMPLE_FLOAT32LE; 1077 | ss.rate = g_samplerate; 1078 | ss.channels = g_num_channels; 1079 | 1080 | pa_simple *s = NULL; 1081 | // int ret = 1; 1082 | int error; 1083 | if (!(s = pa_simple_new(NULL, "dirt", PA_STREAM_PLAYBACK, NULL, 1084 | "playback", &ss, NULL, NULL, &error))) { 1085 | fprintf(stderr, __FILE__": pa_simple_new() failed: %s\n", 1086 | pa_strerror(error)); 1087 | goto finish; 1088 | } 1089 | 1090 | for (;;) { 1091 | 1092 | pa_usec_t latency; 1093 | if ((latency = pa_simple_get_latency(s, &error)) == (pa_usec_t) -1) { 1094 | fprintf(stderr, __FILE__": pa_simple_get_latency() failed: %s\n", 1095 | pa_strerror(error)); 1096 | goto finish; 1097 | } 1098 | //fprintf(stderr, "%f sec \n", ((float)latency)/1000000.0f); 1099 | 1100 | gettimeofday(&tv, NULL); 1101 | double now = ((double) tv.tv_sec + ((double) tv.tv_usec / 1000000.0)); 1102 | 1103 | for (int i=0; i < FRAMES; ++i) { 1104 | double framenow = now + (samplelength * (double) i); 1105 | playback(buf, i, framenow); 1106 | for (int j=0; j < g_num_channels; ++j) { 1107 | interlaced[g_num_channels*i+j] = buf[j][i]; 1108 | } 1109 | dequeue(framenow); 1110 | } 1111 | 1112 | if (pa_simple_write(s, interlaced, sizeof(interlaced), &error) < 0) { 1113 | fprintf(stderr, __FILE__": pa_simple_write() failed: %s\n", pa_strerror(error)); 1114 | goto finish; 1115 | } 1116 | } 1117 | /* Make sure that every single sample was played */ 1118 | if (pa_simple_drain(s, &error) < 0) { 1119 | fprintf(stderr, __FILE__": pa_simple_drain() failed: %s\n", pa_strerror(error)); 1120 | goto finish; 1121 | } 1122 | // ret = 0; 1123 | finish: 1124 | if (s) 1125 | pa_simple_free(s); 1126 | // return ret; 1127 | } 1128 | 1129 | #else 1130 | 1131 | 1132 | static int pa_callback(const void *inputBuffer, void *outputBuffer, 1133 | unsigned long framesPerBuffer, 1134 | const PaStreamCallbackTimeInfo* timeInfo, 1135 | PaStreamCallbackFlags statusFlags, 1136 | void *userData) { 1137 | 1138 | struct timeval tv; 1139 | 1140 | if (epochOffset == 0) { 1141 | gettimeofday(&tv, NULL); 1142 | #ifdef HACK 1143 | epochOffset = 0; 1144 | #else 1145 | epochOffset = ((double) tv.tv_sec + ((double) tv.tv_usec / 1000000.0)) 1146 | - timeInfo->outputBufferDacTime; 1147 | #endif 1148 | /* printf("set offset (%f - %f) to %f\n", ((float) tv.tv_sec + ((float) tv.tv_usec / 1000000.0f)) 1149 | , timeInfo->outputBufferDacTime, epochOffset); */ 1150 | } 1151 | #ifdef HACK 1152 | double now = ((double) tv.tv_sec + ((double) tv.tv_usec / 1000000.0)); 1153 | #else 1154 | double now = timeInfo->outputBufferDacTime; 1155 | #endif 1156 | // printf("%f %f %f\n", timeInfo->outputBufferDacTime, timeInfo->currentTime, Pa_GetStreamTime(stream)); 1157 | float **buffers = (float **) outputBuffer; 1158 | for (int i=0; i < framesPerBuffer; ++i) { 1159 | double framenow = now + (((double) i)/((double) g_samplerate)); 1160 | playback(buffers, i, framenow); 1161 | dequeue(framenow); 1162 | } 1163 | return paContinue; 1164 | } 1165 | #endif 1166 | 1167 | 1168 | 1169 | #ifdef JACK 1170 | void jack_init(bool autoconnect) { 1171 | jack_client = jack_start(jack_callback, autoconnect); 1172 | g_samplerate = jack_get_sample_rate(jack_client); 1173 | } 1174 | #elif PULSE 1175 | void pulse_init() { 1176 | // pulse = pa_threaded_mainloop_new(); 1177 | // pa_threaded_mainloop_set_name(pulse, "dirt"); 1178 | } 1179 | #else 1180 | 1181 | static void StreamFinished( void* userData ) { 1182 | printf( "Stream Completed\n"); 1183 | } 1184 | 1185 | void pa_init(void) { 1186 | PaStreamParameters outputParameters; 1187 | 1188 | PaError err; 1189 | 1190 | printf("init pa\n"); 1191 | 1192 | err = Pa_Initialize(); 1193 | if( err != paNoError ) { 1194 | goto error; 1195 | } 1196 | 1197 | int num = Pa_GetDeviceCount(); 1198 | const PaDeviceInfo *d; 1199 | if (num <0) { 1200 | err = num; 1201 | goto error; 1202 | } 1203 | 1204 | printf("Devices = #%d\n", num); 1205 | for (int i =0; i < num; i++) { 1206 | d = Pa_GetDeviceInfo(i); 1207 | printf("%d = %s: %fHz\n", i, d->name, d->defaultSampleRate); 1208 | } 1209 | 1210 | outputParameters.device = Pa_GetDefaultOutputDevice(); 1211 | if (outputParameters.device == paNoDevice) { 1212 | fprintf(stderr,"Error: No default output device.\n"); 1213 | goto error; 1214 | } 1215 | printf("default device: %s\n", Pa_GetDeviceInfo(outputParameters.device)->name); 1216 | outputParameters.channelCount = g_num_channels; 1217 | outputParameters.sampleFormat = paFloat32 | paNonInterleaved; 1218 | outputParameters.suggestedLatency = 0.050; 1219 | // Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; 1220 | outputParameters.hostApiSpecificStreamInfo = NULL; 1221 | 1222 | char foo[] = "hello"; 1223 | err = Pa_OpenStream( 1224 | &stream, 1225 | NULL, /* no input */ 1226 | &outputParameters, 1227 | g_samplerate, 1228 | PA_FRAMES_PER_BUFFER, 1229 | paNoFlag, 1230 | pa_callback, 1231 | (void *) foo ); 1232 | if( err != paNoError ) { 1233 | printf("failed to open stream.\n"); 1234 | goto error; 1235 | } 1236 | 1237 | err = Pa_SetStreamFinishedCallback( stream, &StreamFinished ); 1238 | if( err != paNoError ) { 1239 | goto error; 1240 | } 1241 | 1242 | #ifdef __linux__ 1243 | printf("setting realtime priority\n"); 1244 | PaAlsa_EnableRealtimeScheduling(stream, 1); 1245 | #endif 1246 | 1247 | err = Pa_StartStream(stream); 1248 | if( err != paNoError ) { 1249 | goto error; 1250 | } 1251 | 1252 | return; 1253 | error: 1254 | fprintf( stderr, "An error occured while using the portaudio stream\n" ); 1255 | fprintf( stderr, "Error number: %d\n", err ); 1256 | fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); 1257 | if( err == paUnanticipatedHostError) { 1258 | const PaHostErrorInfo *hostErrorInfo = Pa_GetLastHostErrorInfo(); 1259 | fprintf( stderr, "Host API error = #%ld, hostApiType = %d\n", hostErrorInfo->errorCode, hostErrorInfo->hostApiType ); 1260 | fprintf( stderr, "Host API error = %s\n", hostErrorInfo->errorText ); 1261 | } 1262 | Pa_Terminate(); 1263 | exit(-1); 1264 | } 1265 | #endif 1266 | 1267 | #ifdef SEND_RMS 1268 | void thread_send_rms() { 1269 | lo_address a = lo_address_new(NULL, "6010"); 1270 | lo_message m; 1271 | 1272 | while(1) { 1273 | m = lo_message_new(); 1274 | for (int i = 0; i < (MAX_ORBIT*2); ++i) { 1275 | if (rms[i].sum_of_squares == 0) { 1276 | lo_message_add_float(m, 0); 1277 | } 1278 | else { 1279 | float result = sqrt(rms[i].sum_of_squares / RMS_SZ); 1280 | lo_message_add_float(m, result); 1281 | } 1282 | } 1283 | lo_send_message(a, "/rmsall", m); 1284 | lo_message_free(m); 1285 | usleep(50000); 1286 | } 1287 | } 1288 | #endif 1289 | 1290 | extern void audio_init(bool dirty_compressor, bool autoconnect, bool late_trigger, unsigned int num_workers, char *sroot, bool shape_gain_comp, bool preload_flag) { 1291 | struct timeval tv; 1292 | 1293 | atexit(audio_close); 1294 | 1295 | gettimeofday(&tv, NULL); 1296 | sampleroot = sroot; 1297 | starttime = (float) tv.tv_sec + ((float) tv.tv_usec / 1000000.0); 1298 | 1299 | delays = calloc(g_num_channels, sizeof(t_line)); 1300 | if (!delays) { 1301 | fprintf(stderr, "no memory to allocate `delays' array\n"); 1302 | exit(1); 1303 | } 1304 | 1305 | pthread_mutex_init(&queue_waiting_lock, NULL); 1306 | pthread_mutex_init(&queue_loading_lock, NULL); 1307 | pthread_mutex_init(&mutex_sounds, NULL); 1308 | 1309 | if (preload_flag) { 1310 | file_preload_samples(sampleroot); 1311 | } 1312 | 1313 | read_file_pool = thpool_init(num_workers); 1314 | if (!read_file_pool) { 1315 | fprintf(stderr, "could not initialize `read_file_pool'\n"); 1316 | exit(1); 1317 | } 1318 | 1319 | #ifdef SEND_RMS 1320 | memset(rms, 0, sizeof(t_rms) * MAX_ORBIT * 2); 1321 | pthread_t rms_t; 1322 | pthread_create(&rms_t, NULL, (void*) thread_send_rms, NULL); 1323 | #endif 1324 | 1325 | #ifdef JACK 1326 | jack_init(autoconnect); 1327 | #elif PULSE 1328 | pthread_t t; 1329 | pthread_create(&t, NULL, (void *(*)(void *)) run_pulse, NULL); 1330 | //sleep(1); 1331 | #else 1332 | pa_init(); 1333 | #endif 1334 | compression_speed = 1000 / g_samplerate; 1335 | use_dirty_compressor = dirty_compressor; 1336 | use_late_trigger = late_trigger; 1337 | use_shape_gain_comp = shape_gain_comp; 1338 | } 1339 | 1340 | extern void audio_close(void) { 1341 | if (delays) free(delays); 1342 | if (read_file_pool) thpool_destroy(read_file_pool); 1343 | 1344 | // free all active sounds, if any 1345 | pthread_mutex_lock(&mutex_sounds); 1346 | for (int i = 0; i < MAX_SOUNDS; ++i) { 1347 | if (sounds[i].active) { 1348 | free_vcf(&sounds[i]); 1349 | free_hpf(&sounds[i]); 1350 | free_bpf(&sounds[i]); 1351 | free_formant_history(&sounds[i]); 1352 | } 1353 | } 1354 | pthread_mutex_unlock(&mutex_sounds); 1355 | } 1356 | 1357 | // Reset sound structure for reutilization 1358 | // 1359 | // This clears structure except for pointer to arrays, to avoid the need of 1360 | // reallocating them. 1361 | static void reset_sound(t_sound* s) { 1362 | t_vcf *old_vcf = s->vcf; 1363 | t_vcf *old_hpf = s->hpf; 1364 | t_vcf *old_bpf = s->bpf; 1365 | double **old_formant_history = s->formant_history; 1366 | 1367 | memset(s, 0, sizeof(t_sound)); 1368 | 1369 | s->vcf = old_vcf; 1370 | s->hpf = old_hpf; 1371 | s->bpf = old_bpf; 1372 | s->formant_history = old_formant_history; 1373 | } 1374 | 1375 | /**/ 1376 | 1377 | t_sound *new_sound() { 1378 | t_sound *result = NULL; 1379 | t_sound *oldest = NULL; 1380 | int dying = 0; 1381 | int cull = playing_n >= MAX_PLAYING; 1382 | 1383 | pthread_mutex_lock(&mutex_sounds); 1384 | 1385 | for (int i = 0; i < MAX_SOUNDS; ++i) { 1386 | if (result == NULL && sounds[i].active == 0) { 1387 | result = &sounds[i]; 1388 | } 1389 | 1390 | if (cull && sounds[i].is_playing == 1) { 1391 | if ((sounds[i].end - sounds[i].position) > ROUNDOFF) { 1392 | if (oldest == NULL || oldest->startT > sounds[i].startT) { 1393 | oldest = &sounds[i]; 1394 | } 1395 | } 1396 | else { 1397 | dying++; 1398 | } 1399 | } 1400 | } 1401 | 1402 | // printf("playing: %d dying: %d \n", playing_n, dying); 1403 | 1404 | // Treat MAX_PLAYING as a soft limit - those about to finish 1405 | // aren't counted. 1406 | if ((playing_n - dying) >= MAX_PLAYING) { 1407 | // printf("hit soft buffer, playing_n %d, dying %d, MAX_PLAYING %d(-%d)\n", playing_n, dying, MAX_PLAYING, MAX_PLAYING_SOFT_BUFFER); 1408 | if (oldest != NULL) { 1409 | // printf("culling sound with end %f, position %f, ROUNDOFF %d\n", oldest->end, oldest->position, ROUNDOFF); 1410 | 1411 | // Rather than stop immediately, set it to finish in ROUNDOFF 1412 | // samples, so the envelope is applied thereby 1413 | // avoiding audio clicks. 1414 | oldest->end = oldest->position + ROUNDOFF; 1415 | } 1416 | } 1417 | 1418 | if (result != NULL) { 1419 | reset_sound(result); 1420 | result->active = 1; 1421 | } 1422 | 1423 | pthread_mutex_unlock(&mutex_sounds); 1424 | // printf("qs: playing %d waiting %d loading %d\n", queue_size(playing), queue_size(waiting), queue_size(loading)); 1425 | return(result); 1426 | } 1427 | -------------------------------------------------------------------------------- /audio.h: -------------------------------------------------------------------------------- 1 | #include "file.h" 2 | #include "config.h" 3 | #include "common.h" 4 | 5 | #define MAXLINE 44100 6 | #define MAX_SOUNDS 512 // includes queue! 7 | 8 | // not a hard limit, after this number sounds will start being 9 | // culled (given ROUNDOFF samples to live to avoid 10 | // discontinuities). 11 | #define MAX_PLAYING 8 12 | 13 | #define ROUNDOFF 16 14 | #define MAX_DB 12 15 | 16 | #ifdef JACK 17 | #include 18 | #include "jack.h" 19 | #define sampletime_t jack_time_t 20 | #else 21 | #define sampletime_t double 22 | #endif 23 | 24 | 25 | typedef struct { 26 | float cutoff; 27 | float res; 28 | float f; 29 | float k; 30 | float p; 31 | float scale; 32 | float r; 33 | float y1; 34 | float y2; 35 | float y3; 36 | float y4; 37 | float oldx; 38 | float oldy1; 39 | float oldy2; 40 | float oldy3; 41 | float x; 42 | } t_vcf; 43 | 44 | typedef struct { 45 | int index; 46 | float last; 47 | float sum; 48 | } t_crs; 49 | 50 | typedef struct { 51 | float samples[MAXLINE]; 52 | int point; 53 | } t_line; 54 | 55 | extern t_line* delays; 56 | extern float line_feedback_delay; 57 | 58 | typedef struct t_node { 59 | int active; 60 | int is_playing; 61 | sampletime_t startT; 62 | char samplename[MAXPATHSIZE+1]; 63 | int is_loop; 64 | union { 65 | t_sample *sample; 66 | t_loop *loop; 67 | }; 68 | unsigned int loop_start; 69 | int channels; 70 | float *items; 71 | struct t_node *next, *prev; 72 | float position; 73 | float speed; 74 | int reverse; 75 | float pan; 76 | float offset; 77 | float start; 78 | float end; 79 | float velocity; 80 | double **formant_history; 81 | int formant_vowelnum; 82 | float cutoff; 83 | float resonance; 84 | t_vcf *vcf; 85 | float accelerate; 86 | int shape; 87 | float shape_k; 88 | int kriole_chunk; 89 | int is_kriole; 90 | int started; 91 | int checks; 92 | float delay; 93 | float delaytime; 94 | float delayfeedback; 95 | float gain; 96 | int cutgroup; 97 | int mono; 98 | int crush; 99 | float crush_bits; 100 | int coarse; 101 | t_crs *coarsef; 102 | float hcutoff; 103 | float hresonance; 104 | t_vcf *hpf; 105 | float bandf; 106 | float bandq; 107 | t_vcf *bpf; 108 | int sample_loop; 109 | int cut_continue; 110 | char unit; 111 | float cps; 112 | double when; 113 | float attack; 114 | float hold; 115 | float release; 116 | float playtime; 117 | int orbit; 118 | int played; 119 | } t_sound; 120 | 121 | typedef struct { 122 | double when; 123 | float cps; 124 | char *samplename; 125 | 126 | float start; 127 | float end; 128 | float speed; 129 | float pan; 130 | float velocity; 131 | int vowelnum; 132 | float cutoff; 133 | float resonance; 134 | float accelerate; 135 | float shape; 136 | int kriole_chunk; 137 | float gain; 138 | int cutgroup; 139 | float delay; 140 | float delaytime; 141 | float delayfeedback; 142 | float crush; 143 | int coarse; 144 | float hcutoff; 145 | float hresonance; 146 | float bandf; 147 | float bandq; 148 | char unit; 149 | int sample_loop; 150 | int sample_n; 151 | float attack; 152 | float hold; 153 | float release; 154 | } t_play_args; 155 | 156 | #ifdef SEND_RMS 157 | typedef struct { 158 | int n; 159 | float sum; 160 | float squares[RMS_SZ]; 161 | float sum_of_squares; 162 | } t_rms; 163 | #endif 164 | 165 | extern int audio_callback(int frames, float *input, float **outputs); 166 | extern void audio_init(bool dirty_compressor, bool autoconnect, bool late_trigger, unsigned int num_workers, char *sampleroot, bool shape_gain_comp, bool preload_flag); 167 | extern void audio_close(void); 168 | extern int audio_play(t_sound*); 169 | t_sound *new_sound(); 170 | 171 | -------------------------------------------------------------------------------- /common.c: -------------------------------------------------------------------------------- 1 | #include "common.h" 2 | #include "config.h" 3 | 4 | int g_num_channels = DEFAULT_CHANNELS; 5 | float g_gain = DEFAULT_GAIN; 6 | int g_samplerate = DEFAULT_SAMPLERATE; 7 | -------------------------------------------------------------------------------- /common.h: -------------------------------------------------------------------------------- 1 | #ifndef __COMMON_H__ 2 | #define __COMMON_H__ 3 | 4 | #include 5 | 6 | #define bool _Bool 7 | 8 | extern int g_num_channels; 9 | extern float g_gain; 10 | extern int g_samplerate; 11 | 12 | #endif // __COMMON_H__ 13 | -------------------------------------------------------------------------------- /config.h: -------------------------------------------------------------------------------- 1 | #ifndef _DIRTCONFIGH_ 2 | #define _DIRTCONFIGH_ 3 | 4 | //#define FEEDBACK 5 | //#define INPUT 6 | #define DEFAULT_OSC_PORT "7771" 7 | 8 | #define DEFAULT_CHANNELS 2 9 | #define MIN_CHANNELS 1 10 | #define MAX_CHANNELS 16 11 | #define DEFAULT_GAIN 2.0 12 | 13 | #define DEFAULT_SAMPLERATE 44100 14 | #define MIN_SAMPLERATE 1024 15 | #define MAX_SAMPLERATE 128000 16 | 17 | #define DEFAULT_WORKERS 2 18 | 19 | // Brings it into being roughly equivalent to superdirt 20 | #define CUTOFFRATIO 30000.0f 21 | 22 | // #define SEND_RMS 23 | 24 | #define MAX_ORBIT 15 25 | 26 | #ifdef SEND_RMS 27 | // 300ms assuming 44100 28 | #define RMS_SZ 13230 29 | #endif 30 | 31 | #endif 32 | -------------------------------------------------------------------------------- /dirt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #ifdef linux 9 | #include 10 | #endif 11 | 12 | #include "common.h" 13 | #include "audio.h" 14 | #include "server.h" 15 | 16 | static int dirty_compressor_flag = 1; 17 | #ifdef JACK 18 | static int jack_auto_connect_flag = 1; 19 | #endif 20 | static int late_trigger_flag = 1; 21 | static int shape_gain_comp_flag = 0; 22 | static int preload_flag = 0; 23 | 24 | #ifdef linux 25 | void sigint_handler(int sig) { 26 | printf("\nCTRL-C detected\n"); 27 | // explicitly call exit on signit so things registered via atexit() fire 28 | exit(-1); 29 | } 30 | #endif 31 | 32 | int main (int argc, char **argv) { 33 | /* Use getopt to parse command-line arguments */ 34 | /* see http://www.gnu.org/savannah-checkouts/gnu/libc/manual/html_node/Getopt.html */ 35 | int c; 36 | int num_channels; 37 | int samplerate; 38 | float gain = 20.0 * log10(g_gain/16.0); 39 | char *osc_port = DEFAULT_OSC_PORT; 40 | char *sampleroot = "./samples"; 41 | char *version = "1.0.0"; 42 | 43 | unsigned int num_workers = DEFAULT_WORKERS; 44 | 45 | #ifdef linux 46 | signal(SIGINT, sigint_handler); 47 | #endif 48 | 49 | while (1) 50 | { 51 | static struct option long_options[] = 52 | { 53 | /* Use flags like so: 54 | {"verbose", no_argument, &verbose_flag, 'V'}*/ 55 | /* Argument styles: no_argument, required_argument, optional_argument */ 56 | {"port", required_argument, 0, 'p'}, 57 | {"channels", required_argument, 0, 'c'}, 58 | {"samplerate", required_argument, 0, 'r'}, 59 | {"dirty-compressor", no_argument, &dirty_compressor_flag, 1}, 60 | {"no-dirty-compressor", no_argument, &dirty_compressor_flag, 0}, 61 | {"shape-gain-compensation", no_argument, &shape_gain_comp_flag, 1}, 62 | {"no-shape-gain-compensation", no_argument, &shape_gain_comp_flag, 0}, 63 | #ifdef JACK 64 | {"jack-auto-connect", no_argument, &jack_auto_connect_flag, 1}, 65 | {"no-jack-auto-connect", no_argument, &jack_auto_connect_flag, 0}, 66 | #endif 67 | {"late-trigger", no_argument, &late_trigger_flag, 1}, 68 | {"no-late-trigger", no_argument, &late_trigger_flag, 0}, 69 | {"samples-root-path", required_argument, 0, 's'}, 70 | {"workers", required_argument, 0, 'w'}, 71 | 72 | {"gain", required_argument, 0, 'g'}, 73 | 74 | {"preload", no_argument, &preload_flag, 1}, 75 | {"no-preload", no_argument, &preload_flag, 0}, 76 | 77 | {"version", no_argument, 0, 'v'}, 78 | {"help", no_argument, 0, 'h'}, 79 | 80 | {0, 0, 0, 0} 81 | }; 82 | 83 | int option_index = 0; 84 | 85 | /* Argument parameters: 86 | no_argument: " " 87 | required_argument: ":" 88 | optional_argument: "::" */ 89 | 90 | c = getopt_long(argc, argv, "c:s:w:g:vh", 91 | long_options, &option_index); 92 | 93 | if (c == -1) 94 | break; 95 | 96 | switch (c) 97 | { 98 | case 0: 99 | /* If this option set a flag, do nothing else now. */ 100 | if (long_options[option_index].flag != 0) break; 101 | 102 | case 'v': 103 | printf("%s\n", version); 104 | return 1; 105 | case 'h': 106 | printf("Usage: dirt [OPTION]...\n" 107 | "\n" 108 | "Dirt - a software sampler, mainly used with Tidal: http://yaxu.org/tidal/\n" 109 | "Released as free software under the terms of the GNU Public License version 3.0 and later.\n" 110 | "\n" 111 | "Arguments:\n" 112 | " -p, --port OSC port to listen to (default: %s)\n" 113 | " -c, --channels number of output channels (default: %u)\n" 114 | #ifndef JACK 115 | " -r, --samplerate samplerate (default: %u)\n" 116 | #endif 117 | " --dirty-compressor enable dirty compressor on audio output (default)\n" 118 | " --no-dirty-compressor disable dirty compressor on audio output\n" 119 | " --shape-gain-compensation enable distortion gain compensation\n" 120 | " --no-shape-gain-compensation disable distortion gain compensation (default)\n" 121 | " -g, --gain gain adjustment (default %f db)\n" 122 | #ifdef JACK 123 | " --jack-auto-connect automatically connect to writable clients (default)\n" 124 | " --no-jack-auto-connect do not connect to writable clients \n" 125 | #endif 126 | " --late-trigger enable sample retrigger after loading (default)\n" 127 | " --no-late-trigger disable sample retrigger after loading\n" 128 | " --preload enable sample preloading at startup\n" 129 | " --no-preload disable sample preloading at startup (default)\n" 130 | " -s --samples-root-path set a samples root directory path\n" 131 | " -w, --workers number of sample-reading workers (default: %u)\n" 132 | " -h, --help display this help and exit\n" 133 | " -v, --version output version information and exit\n", 134 | DEFAULT_OSC_PORT, DEFAULT_CHANNELS, 135 | #ifndef JACK 136 | DEFAULT_SAMPLERATE, 137 | #endif 138 | 20.0*log10(DEFAULT_GAIN/16.0), 139 | DEFAULT_WORKERS); 140 | return 1; 141 | 142 | case 'p': 143 | osc_port = optarg; 144 | break; 145 | case 'c': 146 | num_channels = atoi(optarg); 147 | if (num_channels < MIN_CHANNELS || num_channels > MAX_CHANNELS) { 148 | fprintf(stderr, "invalid number of channels: %u (min: %u, max: %u). resetting to default\n", num_channels, MIN_CHANNELS, MAX_CHANNELS); 149 | num_channels = DEFAULT_CHANNELS; 150 | } 151 | g_num_channels = num_channels; 152 | break; 153 | case 'r': 154 | samplerate = atoi(optarg); 155 | if (samplerate < MIN_SAMPLERATE || samplerate > MAX_SAMPLERATE) { 156 | fprintf(stderr, "invalid number of channels: %u (min: %u, max: %u). resetting to default\n", samplerate, MIN_SAMPLERATE, MAX_SAMPLERATE); 157 | samplerate = DEFAULT_SAMPLERATE; 158 | } 159 | g_samplerate = samplerate; 160 | break; 161 | case 's': 162 | sampleroot = optarg; 163 | break; 164 | case 'w': 165 | num_workers = atoi(optarg); 166 | if (num_workers < 1) { 167 | fprintf(stderr, "invalid number of workers: %u. resetting to default\n", num_workers); 168 | num_workers = DEFAULT_WORKERS; 169 | } 170 | break; 171 | 172 | case 'g': 173 | gain = atof(optarg); 174 | gain = (gain > 40)? 40 : gain; 175 | gain = (gain < -40)?(-40): gain; 176 | g_gain = 16.0 * pow(10.0, gain/20.0); 177 | break; 178 | 179 | case '?': 180 | /* getopt_long will have already printed an error */ 181 | break; 182 | 183 | default: 184 | return 1; 185 | } 186 | } 187 | 188 | fprintf(stderr, "port: %s\n", osc_port); 189 | fprintf(stderr, "channels: %u\n", g_num_channels); 190 | fprintf(stderr, "samplerate: %u\n", g_samplerate); 191 | fprintf(stderr, "gain (dB): %f\n", gain); 192 | fprintf(stderr, "gain factor: %f\n", g_gain); 193 | 194 | if (!dirty_compressor_flag) { 195 | fprintf(stderr, "dirty compressor disabled\n"); 196 | } 197 | if (shape_gain_comp_flag) { 198 | fprintf(stderr, "distortion gain compensation enabled\n"); 199 | } 200 | 201 | #ifdef JACK 202 | if (!jack_auto_connect_flag) { 203 | fprintf(stderr, "port auto-connection disabled\n"); 204 | } 205 | #endif 206 | 207 | if (!late_trigger_flag) { 208 | fprintf(stderr, "late trigger disabled\n"); 209 | } 210 | 211 | if (preload_flag) { 212 | fprintf(stderr, "sample preloading enabled\n"); 213 | } 214 | 215 | fprintf(stderr, "workers: %u\n", num_workers); 216 | 217 | fprintf(stderr, "init audio\n"); 218 | #ifdef JACK 219 | audio_init(dirty_compressor_flag, jack_auto_connect_flag, late_trigger_flag, num_workers, sampleroot, shape_gain_comp_flag, preload_flag); 220 | #else 221 | audio_init(dirty_compressor_flag, true, late_trigger_flag, num_workers, sampleroot, shape_gain_comp_flag, preload_flag); 222 | #endif 223 | 224 | fprintf(stderr, "init open sound control\n"); 225 | server_init(osc_port); 226 | 227 | sleep(-1); 228 | return(0); 229 | } 230 | -------------------------------------------------------------------------------- /file.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "file.h" 11 | #include "common.h" 12 | #include "segment.h" 13 | 14 | t_sample *samples[MAXSAMPLES]; 15 | int sample_count = 0; 16 | 17 | pthread_mutex_t mutex_samples; 18 | bool mutex_samples_init = false; 19 | 20 | t_loop *new_loop(float seconds) { 21 | t_loop *result = (t_loop *) calloc(1, sizeof(t_loop)); 22 | //result->chunksz = 2048 * 2; 23 | result->chunksz = 2048; 24 | result->max_frames = result->frames = seconds * (float) g_samplerate; 25 | result->items = (float *) calloc(result->frames, sizeof(double)); 26 | result->in = (float *) calloc(result->chunksz, sizeof(double)); 27 | result->now = 0; 28 | result->loops = 0; 29 | return(result); 30 | } 31 | 32 | void free_loop(t_loop *loop) { 33 | if (loop) { 34 | if (loop->items) free(loop->items); 35 | if (loop->in) free(loop->in); 36 | free(loop); 37 | } 38 | } 39 | 40 | t_sample *find_sample (char *samplename) { 41 | int c; 42 | t_sample *sample = NULL; 43 | 44 | for(c = 0; c < sample_count; ++c) { 45 | if(strcmp(samples[c]->name, samplename) == 0) { 46 | sample = samples[c]; 47 | break; 48 | } 49 | } 50 | return(sample); 51 | } 52 | 53 | int wav_filter (const struct dirent *d) { 54 | if (strlen(d->d_name) > 4) { 55 | return(strcasecmp(d->d_name + strlen(d->d_name) - 4, ".wav") == 0); 56 | } 57 | return(0); 58 | } 59 | 60 | void fix_samplerate (t_sample *sample) { 61 | SRC_DATA data; 62 | int max_output_frames; 63 | int channels = sample->info->channels; 64 | 65 | //printf("start frames: %d\n", sample->info->frames); 66 | //printf("compare %d and %d\n", sample->info->samplerate, g_samplerate); 67 | if (sample->info->samplerate == g_samplerate) { 68 | return; 69 | } 70 | data.src_ratio = (float) g_samplerate / (float) sample->info->samplerate; 71 | //printf("ratio: %d / %d = %f\n", sample->info->samplerate, samplerate, data.src_ratio); 72 | max_output_frames = sample->info->frames * data.src_ratio + 32; 73 | 74 | data.data_in = sample->items; 75 | data.input_frames = sample->info->frames; 76 | 77 | data.data_out = (float *) calloc(1, sizeof(float) 78 | * max_output_frames 79 | * channels 80 | ); 81 | data.output_frames = max_output_frames; 82 | 83 | src_simple(&data, SRC_SINC_BEST_QUALITY, channels); 84 | 85 | if (sample->items) free(sample->items); 86 | sample->items = data.data_out; 87 | sample->info->samplerate = g_samplerate; 88 | sample->info->frames = data.output_frames_gen; 89 | //printf("end samplerate: %d frames: %d\n", (int) sample->info->samplerate, sample->info->frames); 90 | } 91 | 92 | extern int file_count_samples(char *set, const char *sampleroot) { 93 | int result = 0; 94 | struct dirent **namelist; 95 | char path[MAXPATHSIZE * 2 + 24]; 96 | 97 | snprintf(path, sizeof(path), "%s/%s", sampleroot, set); 98 | result = scandir(path, &namelist, wav_filter, alphasort); 99 | 100 | if (result >= 0) { 101 | free(namelist); 102 | } 103 | else { 104 | // Some error reading the folder 105 | result = 0; 106 | } 107 | 108 | return(result); 109 | } 110 | 111 | extern t_sample *file_get(char *samplename, const char *sampleroot) { 112 | t_sample* sample; 113 | 114 | sample = find_sample(samplename); 115 | 116 | // If sample was not in cache, read it from disk asynchronously 117 | if (sample == NULL) { 118 | // Initialize mutexes if needed 119 | if (!mutex_samples_init) { 120 | pthread_mutex_init(&mutex_samples, NULL); 121 | mutex_samples_init = true; 122 | } 123 | 124 | SNDFILE *sndfile; 125 | char path[2 * MAXPATHSIZE + 24]; 126 | char error[62]; 127 | sf_count_t count; 128 | float *items; 129 | SF_INFO *info; 130 | char set[MAXPATHSIZE]; 131 | char sep[2]; 132 | int set_n = 0; 133 | struct dirent **namelist; 134 | 135 | // load it from disk 136 | if (sscanf(samplename, "%[a-z0-9A-Z]%[/:]%d", set, sep, &set_n)) { 137 | int n; 138 | snprintf(path, sizeof(path), "%s/%s", sampleroot, set); 139 | //printf("looking in %s\n", set); 140 | n = scandir(path, &namelist, wav_filter, alphasort); 141 | if (n > 0) { 142 | snprintf(path, sizeof(path), 143 | "%s/%s/%s", sampleroot, set, namelist[set_n % n]->d_name); 144 | while (n--) { 145 | free(namelist[n]); 146 | } 147 | free(namelist); 148 | } else { 149 | snprintf(path, sizeof(path), "%s/%s", sampleroot, samplename); 150 | } 151 | } else { 152 | snprintf(path, MAXPATHSIZE -1, "%s/%s", sampleroot, samplename); 153 | } 154 | 155 | info = (SF_INFO *) calloc(1, sizeof(SF_INFO)); 156 | 157 | //printf("opening %s.\n", path); 158 | 159 | if ((sndfile = (SNDFILE *) sf_open(path, SFM_READ, info)) == NULL) { 160 | printf("could not open sound file %s for sample %s\n", path, samplename); 161 | free(info); 162 | } else { 163 | items = (float *) calloc(1, sizeof(float) * info->frames * info->channels); 164 | //snprintf(error, (size_t) 61, "hm: %d\n", sf_error(sndfile)); 165 | //perror(error); 166 | count = sf_read_float(sndfile, items, info->frames * info->channels); 167 | //snprintf(error, (size_t) 61, "count: %d frames: %d channels: %d\n", (int) count, (int) info->frames, info->channels); 168 | //perror(error); 169 | 170 | if (count == info->frames * info->channels) { 171 | sample = (t_sample *) calloc(1, sizeof(t_sample)); 172 | strncpy(sample->name, samplename, MAXPATHSIZE - 1); 173 | sample->info = info; 174 | sample->items = items; 175 | 176 | } else { 177 | snprintf(error, (size_t) 61, "didn't get the right number of items: %d vs %d %d\n", (int) count, (int) info->frames * info->channels, sf_error(sndfile)); 178 | perror(error); 179 | free(info); 180 | free(items); 181 | } 182 | sf_close(sndfile); 183 | } 184 | 185 | if (sample) { 186 | fix_samplerate(sample); 187 | sample->onsets = NULL; 188 | //sample->onsets = segment_get_onsets(sample); 189 | } 190 | // else an error message will already have been printed 191 | 192 | // If sample was succesfully read, load it into cache 193 | if (sample) { 194 | pthread_mutex_lock(&mutex_samples); 195 | samples[sample_count++] = sample; 196 | pthread_mutex_unlock(&mutex_samples); 197 | } 198 | } 199 | 200 | return(sample); 201 | } 202 | 203 | extern t_sample *file_get_from_cache(char *samplename) { 204 | return find_sample(samplename); 205 | } 206 | 207 | 208 | extern void file_preload_samples(const char *sampleroot) { 209 | struct dirent* dent; 210 | DIR* srcdir = opendir(sampleroot); 211 | 212 | // sample set name 213 | char samplename[MAXPATHSIZE + 24]; 214 | 215 | if (srcdir == NULL) { 216 | return; 217 | } 218 | fprintf(stderr, "preloading ..\n"); 219 | while((dent = readdir(srcdir)) != NULL) { 220 | struct stat st; 221 | if(strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0) 222 | continue; 223 | 224 | if (fstatat(dirfd(srcdir), dent->d_name, &st, 0) < 0) { 225 | continue; 226 | } 227 | 228 | if (S_ISDIR(st.st_mode)) { 229 | int n = file_count_samples(dent->d_name, sampleroot); 230 | for (int i = 0; i < n; ++i) { 231 | snprintf(samplename, sizeof(samplename), "%s:%d", dent->d_name, i); 232 | fprintf(stderr, "> %s\n", samplename); 233 | file_get(samplename, sampleroot); 234 | } 235 | } 236 | } 237 | fprintf(stderr, "preload done.\n"); 238 | closedir(srcdir); 239 | } 240 | -------------------------------------------------------------------------------- /file.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAXSAMPLES 1024 5 | #define MAXFILES 4096 6 | #define MAXPATHSIZE 256 7 | 8 | typedef struct { 9 | char name[MAXPATHSIZE]; 10 | SF_INFO *info; 11 | float *items; 12 | int *onsets; 13 | } t_sample; 14 | 15 | typedef struct { 16 | unsigned int max_frames; 17 | unsigned int frames; 18 | unsigned int now; 19 | int loops; 20 | unsigned int chunksz; 21 | unsigned int since_chunk; 22 | unsigned int chunk_n; 23 | float *items; 24 | float *in; 25 | //fvec_t *in; 26 | //fvec_t *ibuf; 27 | 28 | unsigned int win_s; 29 | unsigned int hop_s; 30 | unsigned int samplerate; 31 | unsigned int channels; 32 | 33 | int initialised; 34 | } t_loop; 35 | 36 | int wav_filter (const struct dirent *d); 37 | extern void file_set_samplerate(int s); 38 | extern t_sample *file_get(char *samplename, const char *sampleroot); 39 | extern t_sample *file_get_from_cache(char *samplename); 40 | t_loop *new_loop(float seconds); 41 | void free_loop(t_loop*); 42 | extern int file_count_samples(char *set, const char *sampleroot); 43 | extern void file_preload_samples(const char *sampleroot); 44 | -------------------------------------------------------------------------------- /jack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include "jack.h" 10 | #include "config.h" 11 | 12 | jack_client_t *client; 13 | jack_port_t **output_ports; 14 | 15 | #ifdef INPUT 16 | jack_port_t *input_port; 17 | #endif 18 | 19 | int process(jack_nframes_t nframes, void *arg) { 20 | jack_default_audio_sample_t *out[g_num_channels+1]; 21 | #ifdef INPUT 22 | jack_default_audio_sample_t *in; 23 | #endif 24 | t_callback callback = (t_callback) arg; 25 | int i; 26 | 27 | for (i = 0; i < g_num_channels; ++i) { 28 | out[i] = jack_port_get_buffer(output_ports[i], nframes); 29 | } 30 | 31 | #ifdef INPUT 32 | in = jack_port_get_buffer(input_port, nframes); 33 | callback(nframes, in, out); 34 | #else 35 | callback(nframes, NULL, out); 36 | #endif 37 | 38 | 39 | return 0; 40 | 41 | } 42 | 43 | void jack_shutdown(void *arg) { 44 | if (output_ports) free(output_ports); 45 | exit(1); 46 | } 47 | 48 | extern jack_client_t *jack_start(t_callback callback, bool autoconnect) { 49 | const char *client_name = "dirt"; 50 | const char *server_name = NULL; 51 | jack_options_t options = JackNullOption; 52 | jack_status_t status; 53 | int i; 54 | char portname[24]; 55 | 56 | /* open a client connection to the JACK server */ 57 | 58 | client = jack_client_open(client_name, options, &status, server_name); 59 | if (client == NULL) { 60 | fprintf(stderr, "jack_client_open() failed, " 61 | "status = 0x%2.0x\n", status); 62 | if (status & JackServerFailed) { 63 | fprintf(stderr, "Unable to connect to JACK server\n"); 64 | } 65 | exit(1); 66 | } 67 | if (status & JackServerStarted) { 68 | fprintf(stderr, "JACK server started\n"); 69 | } 70 | if (status & JackNameNotUnique) { 71 | client_name = jack_get_client_name(client); 72 | fprintf(stderr, "unique name `%s' assigned\n", client_name); 73 | } 74 | 75 | jack_set_process_callback(client, process, (void *) callback); 76 | 77 | jack_on_shutdown(client, jack_shutdown, 0); 78 | 79 | printf("engine sample rate: %" PRIu32 "\n", 80 | jack_get_sample_rate(client)); 81 | 82 | #ifdef INPUT 83 | strcpy(portname, "input"); 84 | input_port = jack_port_register(client, portname, 85 | JACK_DEFAULT_AUDIO_TYPE, 86 | JackPortIsInput, 0); 87 | 88 | if (input_port == NULL) { 89 | fprintf(stderr, "no JACK input ports available\n"); 90 | exit(1); 91 | } 92 | #endif 93 | 94 | output_ports = malloc((g_num_channels + 1) * sizeof(jack_port_t*)); 95 | if (!output_ports) { 96 | fprintf(stderr, "no memory to allocate `output_ports'\n"); 97 | exit(1); 98 | } 99 | 100 | for (i = 0; i < g_num_channels; ++i) { 101 | snprintf(portname, sizeof(portname), "output_%d", i); 102 | output_ports[i] = jack_port_register(client, portname, 103 | JACK_DEFAULT_AUDIO_TYPE, 104 | JackPortIsOutput, 0); 105 | if (output_ports[i] == NULL) { 106 | fprintf(stderr, "no more JACK ports available\n"); 107 | if (output_ports) free(output_ports); 108 | exit(1); 109 | } 110 | } 111 | 112 | output_ports[g_num_channels] = NULL; 113 | 114 | if (jack_activate(client)) { 115 | fprintf(stderr, "cannot activate client"); 116 | if (output_ports) free(output_ports); 117 | exit(1); 118 | } 119 | 120 | if (autoconnect) { 121 | const char **ports; 122 | ports = jack_get_ports(client, NULL, NULL, 123 | JackPortIsPhysical|JackPortIsInput); 124 | if (!ports) { 125 | fprintf(stderr, "cannot find any physical capture ports\n"); 126 | } else { 127 | for (i = 0; i < g_num_channels; ++i) { 128 | if (ports[i] == NULL) { 129 | break; 130 | } 131 | //sprintf(portname, "output_%d", i); 132 | if (jack_connect(client, jack_port_name(output_ports[i]), ports[i])) { 133 | fprintf(stderr, "cannot connect output ports\n"); 134 | } 135 | } 136 | free(ports); 137 | } 138 | 139 | #ifdef INPUT 140 | ports = jack_get_ports(client, NULL, NULL, 141 | JackPortIsPhysical|JackPortIsOutput); 142 | //strcpy(portname, "input"); 143 | if (!ports) { 144 | fprintf(stderr, "cannot find any physical capture ports\n"); 145 | } else { 146 | if (jack_connect(client, ports[0], jack_port_name(input_port))) { 147 | fprintf(stderr, "cannot connect input port\n"); 148 | } 149 | free(ports); 150 | } 151 | #endif 152 | } 153 | 154 | return(client); 155 | } 156 | 157 | -------------------------------------------------------------------------------- /jack.h: -------------------------------------------------------------------------------- 1 | #ifndef _DIRTJACKH_ 2 | #define _DIRTJACKH_ 3 | #include 4 | #include "common.h" 5 | 6 | typedef int (*t_callback)(int, float *, float **); 7 | 8 | extern jack_client_t *jack_start(t_callback callback, bool autoconnect); 9 | #endif 10 | -------------------------------------------------------------------------------- /jobqueue.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "jobqueue.h" 6 | 7 | typedef struct { 8 | job_t job; 9 | void* next; 10 | } entry_t; 11 | 12 | struct jobqueue { 13 | entry_t* head; 14 | entry_t* tail; 15 | unsigned int size; 16 | pthread_mutex_t lock; 17 | }; 18 | 19 | jobqueue_t* jobqueue_init() { 20 | jobqueue_t* q = malloc(sizeof(jobqueue_t)); 21 | if (!q) return NULL; 22 | 23 | q->head = NULL; 24 | q->tail = NULL; 25 | q->size = 0; 26 | pthread_mutex_init(&q->lock, NULL); 27 | 28 | return q; 29 | } 30 | 31 | bool jobqueue_push(jobqueue_t* q, job_t j) { 32 | entry_t* e = malloc(sizeof(entry_t)); 33 | if (!e) return false; 34 | e->job = j; 35 | e->next = NULL; 36 | 37 | pthread_mutex_lock(&q->lock); 38 | 39 | if (q->head == NULL) { 40 | q->head = e; 41 | q->tail = e; 42 | } else { 43 | q->tail->next = e; 44 | q->tail = e; 45 | } 46 | q->size++; 47 | 48 | pthread_mutex_unlock(&q->lock); 49 | 50 | return true; 51 | } 52 | 53 | bool jobqueue_is_empty(const jobqueue_t* q) { 54 | return q->head == NULL; 55 | } 56 | 57 | job_t* jobqueue_top(jobqueue_t* q) { 58 | pthread_mutex_lock(&q->lock); 59 | 60 | assert(q->head != NULL); 61 | job_t* top = &q->head->job; 62 | 63 | pthread_mutex_unlock(&q->lock); 64 | 65 | return top; 66 | } 67 | 68 | bool jobqueue_pop (jobqueue_t* q, job_t* j) { 69 | pthread_mutex_lock(&q->lock); 70 | 71 | if (q->head == NULL) { 72 | pthread_mutex_unlock(&q->lock); 73 | return false; 74 | } 75 | 76 | entry_t* top = q->head; 77 | 78 | if (j) *j = top->job; 79 | 80 | if (q->head == q->tail) { 81 | q->head = q->tail = NULL; 82 | } else { 83 | q->head = q->head->next; 84 | } 85 | q->size--; 86 | 87 | pthread_mutex_unlock(&q->lock); 88 | 89 | free(top); 90 | 91 | return true; 92 | } 93 | 94 | unsigned int jobqueue_size(const jobqueue_t* q) { 95 | return q->size; 96 | } 97 | 98 | void jobqueue_destroy(jobqueue_t* q) { 99 | pthread_mutex_lock(&q->lock); 100 | 101 | entry_t* cur = q->head; 102 | while (cur != NULL) { 103 | entry_t* next = cur->next; 104 | free(cur); 105 | cur = next; 106 | }; 107 | 108 | pthread_mutex_unlock(&q->lock); 109 | pthread_mutex_destroy(&q->lock); 110 | 111 | free(q); 112 | } 113 | -------------------------------------------------------------------------------- /jobqueue.h: -------------------------------------------------------------------------------- 1 | #ifndef __JOBQUEUE_H__ 2 | #define __JOBQUEUE_H__ 3 | 4 | #include 5 | 6 | 7 | typedef struct { 8 | void* (*function)(void* args); // function pointer 9 | void* args; // function's argument 10 | } job_t; 11 | #define JOB(function, args) ((job_t) { function, args }) 12 | 13 | typedef struct jobqueue jobqueue_t; 14 | 15 | 16 | // Initialize job queue 17 | // 18 | jobqueue_t* jobqueue_init (); 19 | 20 | // Push a job onto the queue 21 | // 22 | bool jobqueue_push (jobqueue_t* q, job_t j); 23 | 24 | // Determine if queue is empty 25 | // 26 | bool jobqueue_is_empty(const jobqueue_t* q); 27 | 28 | // Returns a reference to the job at the top of the queue 29 | job_t* jobqueue_top (jobqueue_t* q); 30 | 31 | // Removes top job and returns a copy of it 32 | // 33 | // If queue is empty, function returns false. Otherwise, returns true and 34 | // copies job onto j. If j is not NULL, the top job is copied to the job 35 | // referenced by t. The job structure must be created beforehand by the 36 | // calling thread. 37 | // 38 | bool jobqueue_pop (jobqueue_t* q, job_t* j); 39 | 40 | // Returns the size or number of jobs in queue 41 | // 42 | unsigned int jobqueue_size (const jobqueue_t* q); 43 | 44 | // De-allocates queue and its entries 45 | // 46 | // Job structures are not freed, the user is responsible 47 | // of freeing them afterwards. 48 | // 49 | void jobqueue_destroy (jobqueue_t* q); 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /pitch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "file.h" 6 | #include 7 | 8 | extern void pitch_init(t_loop *loop, int samplerate) { 9 | // loop->win_s = 1024; 10 | // loop->hop_s = loop->win_s/4; 11 | loop->win_s = loop->chunksz; 12 | loop->hop_s = loop->chunksz; 13 | loop->samplerate = samplerate; 14 | loop->channels = 1; 15 | 16 | xtract_init_fft(loop->chunksz, XTRACT_SPECTRUM); 17 | 18 | loop->initialised = 1; 19 | } 20 | 21 | void pitch_destruct(t_loop *loop) { 22 | } 23 | 24 | extern float *pitch_calc(t_loop *loop) { 25 | float rmsAmplitude = 0; 26 | double pitch = -1; 27 | static float result[3]; 28 | result[0] = -1; 29 | result[1] = -1; 30 | result[2] = -1; 31 | 32 | if (loop->initialised == 0) { 33 | return(NULL); 34 | } 35 | 36 | int j = (loop->now - loop->chunksz) % loop->frames; 37 | 38 | for (int i = 0; i < loop->chunksz; i++){ 39 | rmsAmplitude += sqrt(loop->items[j]*loop->items[j]); 40 | loop->in[i] = (double) loop->items[j]; 41 | ++j; 42 | if (j >= loop->frames) { 43 | j = 0; 44 | } 45 | } 46 | 47 | rmsAmplitude /= loop->chunksz; 48 | 49 | if( rmsAmplitude > 0.005 ){ 50 | double flux = -1; 51 | double centroid = -1; 52 | double param[4]; 53 | double spectrum[loop->chunksz]; 54 | 55 | xtract[XTRACT_WAVELET_F0](loop->in, loop->chunksz, &loop->samplerate, &pitch); 56 | 57 | param[0] = (double) loop->samplerate / (double)loop->chunksz; 58 | param[1] = XTRACT_MAGNITUDE_SPECTRUM; 59 | param[2] = 0.f; 60 | param[3] = 0.f; 61 | 62 | xtract[XTRACT_SPECTRUM](loop->in, loop->chunksz, ¶m[0], spectrum); 63 | 64 | xtract_spectral_centroid(spectrum, loop->chunksz, NULL, ¢roid); 65 | 66 | // order 67 | param[0] = 1; 68 | // type 69 | param[1] = XTRACT_POSITIVE_SLOPE; 70 | xtract[XTRACT_FLUX](loop->in, loop->chunksz, ¶m, &flux); 71 | 72 | printf("pitches: %f %f %f %f\n", pitch, flux, centroid, rmsAmplitude); 73 | result[0] = pitch; 74 | result[1] = flux; 75 | result[2] = centroid; 76 | } 77 | return(result); 78 | } 79 | 80 | /* 81 | extern int *segment_get_onsets(t_sample *sample) { 82 | int *result; 83 | pitch_init(sample->info->channels); 84 | result = pitch_process(sample, sample->items, sample->info->frames); 85 | pitch_destruct(); 86 | return(result); 87 | } 88 | */ 89 | -------------------------------------------------------------------------------- /pitch.h: -------------------------------------------------------------------------------- 1 | 2 | extern void pitch_init(t_loop *loop, int samplerate); 3 | extern float *pitch_calc(t_loop *loop); 4 | -------------------------------------------------------------------------------- /segment.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "file.h" 6 | 7 | uint_t overlap_size = 256; 8 | aubio_pvoc_t * pv; 9 | fvec_t * ibuf; 10 | cvec_t * fftgrain; 11 | aubio_onsetdetection_t *o; 12 | aubio_onsetdetection_type type_onset = aubio_onset_kl; 13 | aubio_onsetdetection_type type_onset2 = aubio_onset_complex; 14 | fvec_t *onset; 15 | fvec_t *onset2; 16 | 17 | smpl_t threshold = 0.3; 18 | smpl_t silence = -90.; 19 | uint_t buffer_size = 512; /*1024;*/ 20 | aubio_pickpeak_t * parms; 21 | unsigned int pos = 0; /*frames%dspblocksize*/ 22 | uint_t channels; 23 | aubio_onsetdetection_t *o2; 24 | int usedoubled = 1; 25 | #define MAXONSETS 128 26 | int onsets[MAXONSETS]; 27 | int onset_n = 0; 28 | 29 | void aubio_init(int c) { 30 | channels = c; 31 | /* phase vocoder */ 32 | pv = new_aubio_pvoc(buffer_size, overlap_size, channels); 33 | ibuf = new_fvec(overlap_size, channels); 34 | fftgrain = new_cvec(buffer_size, channels); 35 | o = new_aubio_onsetdetection(type_onset, buffer_size, channels); 36 | parms = new_aubio_peakpicker(threshold); 37 | onset = new_fvec(1, channels); 38 | pos = 0; 39 | onset_n = 0; 40 | if (usedoubled) { 41 | o2 = new_aubio_onsetdetection(type_onset2,buffer_size,channels); 42 | onset2 = new_fvec(1 , channels); 43 | } 44 | } 45 | 46 | void aubio_destruct() { 47 | del_aubio_pvoc(pv); 48 | del_fvec(ibuf); 49 | del_cvec(fftgrain); 50 | del_aubio_onsetdetection(o); 51 | del_aubio_peakpicker(parms); 52 | del_fvec(onset); 53 | if (usedoubled) { 54 | del_aubio_onsetdetection(o2); 55 | del_fvec(onset2); 56 | } 57 | } 58 | 59 | int *aubio_process(t_sample *sample, float *input, sf_count_t nframes) { 60 | unsigned int j, i; 61 | 62 | int *result; 63 | 64 | for (j=0; j < nframes; j++) { 65 | for (i=0; i < channels; i++) { 66 | /* write input to datanew */ 67 | fvec_write_sample(ibuf, input[channels*j+i], i, pos % overlap_size); 68 | } 69 | 70 | /*time for fft*/ 71 | if (pos % overlap_size == (overlap_size - 1)) { 72 | int isonset; 73 | /* block loop */ 74 | aubio_pvoc_do(pv, ibuf, fftgrain); 75 | aubio_onsetdetection(o, fftgrain, onset); 76 | if (usedoubled) { 77 | aubio_onsetdetection(o2,fftgrain, onset2); 78 | onset->data[0][0] *= onset2->data[0][0]; 79 | } 80 | isonset = aubio_peakpick_pimrt(onset, parms); 81 | if (isonset) { 82 | /* test for silence */ 83 | if (aubio_silence_detection(ibuf, silence)==1) { 84 | printf("silence.\n"); 85 | isonset=0; 86 | } 87 | else { 88 | printf("onset! %d\n", pos); 89 | onsets[onset_n++] = pos; 90 | } 91 | } 92 | } 93 | pos++; 94 | } 95 | 96 | result = (int *) calloc(1, sizeof(int) * (onset_n + 1)); 97 | memcpy(result, onsets, sizeof(int) * onset_n); 98 | result[onset_n] = -1; 99 | printf("found %d onsets\n", onset_n); 100 | 101 | return(result); 102 | } 103 | 104 | extern int *segment_get_onsets(t_sample *sample) { 105 | int *result; 106 | aubio_init(sample->info->channels); 107 | result = aubio_process(sample, sample->items, sample->info->frames); 108 | aubio_destruct(); 109 | return(result); 110 | } 111 | -------------------------------------------------------------------------------- /segment.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | extern int *segment_get_onsets(t_sample *sound); 4 | -------------------------------------------------------------------------------- /server.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "server.h" 12 | #include "audio.h" 13 | #include "config.h" 14 | 15 | #ifdef ZEROMQ 16 | #include 17 | #define MAXOSCSZ 1024 18 | #endif 19 | 20 | void error(int num, const char *m, const char *path); 21 | 22 | int trigger_handler(const char *path, const char *types, lo_arg **argv, 23 | int argc, void *data, void *user_data); 24 | 25 | int generic_handler(const char *path, const char *types, lo_arg **argv, 26 | int argc, void *data, void *user_data); 27 | 28 | /**/ 29 | 30 | void error(int num, const char *msg, const char *path) { 31 | printf("liblo server error %d in path %s: %s\n", num, path, msg); 32 | } 33 | 34 | /**/ 35 | 36 | int generic_handler(const char *path, const char *types, lo_arg **argv, 37 | int argc, void *data, void *user_data) { 38 | int i; 39 | 40 | printf("path: <%s>\n", path); 41 | for (i=0; ii + (((double) argv[1]->i) / 1000000.0); 59 | #ifdef SUBLATENCY 60 | when -= SUBLATENCY; 61 | #endif 62 | int poffset = 2; 63 | 64 | float cps = argv[2]->f; 65 | poffset = 3; 66 | // printf("timing info: when, cps = %f\t%f a %i b %i\n", when, cps, argv[0]->i, argv[1]->i); 67 | 68 | char *sample_name = (char *) argv[0+poffset]; 69 | 70 | float offset = argv[1+poffset]->f; 71 | 72 | //when += offset; 73 | 74 | float start = argv[2+poffset]->f; 75 | float end = argv[3+poffset]->f; 76 | float speed = argv[4+poffset]->f; 77 | float pan = argv[5+poffset]->f; 78 | float velocity = argv[6+poffset]->f; 79 | char *vowel_s = (char *) argv[7+poffset]; 80 | float cutoff = argv[8+poffset]->f; 81 | float resonance = argv[9+poffset]->f; 82 | float accelerate = argv[10+poffset]->f; 83 | float shape = argv[11+poffset]->f; 84 | 85 | float gain = argc > (13+poffset) ? argv[13+poffset]->f : 0; 86 | int cutgroup = argc > (14+poffset) ? argv[14+poffset]->i : 0; 87 | 88 | float delay = argc > (15+poffset) ? argv[15+poffset]->f : 0; 89 | float delaytime = argc > (16+poffset) ? argv[16+poffset]->f : 0; 90 | float delayfeedback = argc > (17+poffset) ? argv[17+poffset]->f : 0; 91 | 92 | float crush = argc > (18+poffset) ? argv[18+poffset]->f : 0; 93 | int coarse = argc > (19+poffset) ? argv[19+poffset]->i : 0; 94 | float hcutoff = argc > (20+poffset) ? argv[20+poffset]->f : 0; 95 | float hresonance = argc > (21+poffset) ? argv[21+poffset]->f : 0; 96 | float bandf = argc > (22+poffset) ? argv[22+poffset]->f : 0; 97 | float bandq = argc > (23+poffset) ? argv[23+poffset]->f : 0; 98 | 99 | char *unit_name = argc > (24+poffset) ? (char *) argv[24+poffset] : "r"; 100 | int sample_loop = argc > (25+poffset) ? floor(argv[25+poffset]->f) : 0; 101 | int sample_n = argc > (26+poffset) ? floor(argv[26+poffset]->f) : 0; 102 | 103 | float attack = argc > (27+poffset) ? argv[27+poffset]->f : 0; 104 | float hold = argc > (28+poffset) ? argv[28+poffset]->f : 0; 105 | float release = argc > (29+poffset) ? argv[29+poffset]->f : 0; 106 | 107 | int orbit = argc > (30+poffset) ? argv[30+poffset]->i : 0; 108 | //printf("orb: %d\n", orbit); 109 | static bool extraWarned = false; 110 | if (argc > 31+poffset && !extraWarned) { 111 | printf("play server unexpectedly received extra parameters, maybe update Dirt?\n"); 112 | extraWarned = true; 113 | } 114 | 115 | if (speed == 0) { 116 | return(0); 117 | } 118 | 119 | int vowelnum = -1; 120 | 121 | switch(vowel_s[0]) { 122 | case 'a': case 'A': vowelnum = 0; break; 123 | case 'e': case 'E': vowelnum = 1; break; 124 | case 'i': case 'I': vowelnum = 2; break; 125 | case 'o': case 'O': vowelnum = 3; break; 126 | case 'u': case 'U': vowelnum = 4; break; 127 | } 128 | //printf("vowel: %s num: %d\n", vowel_s, vowelnum); 129 | 130 | int unit = -1; 131 | switch(unit_name[0]) { 132 | // rate 133 | case 'r': case 'R': unit = 'r'; break; 134 | // sec 135 | case 's': case 'S': unit = 's'; break; 136 | // cycle 137 | case 'c': case 'C': unit = 'c'; break; 138 | } 139 | 140 | t_sound *sound = new_sound(); 141 | if (sound == NULL) { 142 | //printf("hit max sounds (%d)\n", MAXSOUNDS); 143 | return(0); 144 | } 145 | sound->active = 1; 146 | sound->speed = speed; 147 | sound->pan = pan; 148 | sound->start = start; 149 | sound->end = end; 150 | sound->velocity = velocity; 151 | sound->formant_vowelnum = vowelnum; 152 | sound->cutoff = cutoff / CUTOFFRATIO; 153 | sound->resonance = resonance; 154 | sound->accelerate = accelerate; 155 | sound->shape = (shape != 0); 156 | shape = fabs(shape); 157 | shape = (shape > 0.99f)?0.99f:shape; 158 | sound->shape_k = (2.0f * shape) / (1.0f - shape); 159 | sound->delay = delay; 160 | sound->delaytime = delaytime; 161 | sound->delayfeedback = delayfeedback; 162 | sound->gain = powf(gain/2, 4); 163 | sound->cutgroup = cutgroup; 164 | sound->crush = crush; 165 | sound->coarse = coarse; 166 | sound->hcutoff = hcutoff; 167 | sound->hresonance = hresonance; 168 | sound->bandf = bandf; 169 | sound->bandq = bandq; 170 | sound->sample_loop = sample_loop; 171 | sound->unit = unit; 172 | sound->offset = offset; 173 | sound->cps = cps; 174 | sound->when = when; 175 | sound->orbit = (orbit <= MAX_ORBIT) ? orbit : MAX_ORBIT; 176 | //printf("orbit: %d\n", sound->orbit); 177 | if (sample_n) { 178 | sample_n = abs(sample_n); 179 | snprintf(sound->samplename, MAXPATHSIZE, "%s:%d", 180 | sample_name, 181 | sample_n); 182 | } 183 | else { 184 | strncpy(sound->samplename, sample_name, MAXPATHSIZE); 185 | } 186 | sound->attack = attack; 187 | sound->hold = hold; 188 | sound->release = release; 189 | 190 | audio_play(sound); 191 | 192 | return(0); 193 | } 194 | 195 | /**/ 196 | 197 | #ifdef ZEROMQ 198 | void *zmqthread(void *data){ 199 | void *context = zmq_ctx_new (); 200 | void *subscriber = zmq_socket (context, ZMQ_SUB); 201 | void *buffer = (void *) malloc(MAXOSCSZ); 202 | 203 | int rc = zmq_connect (subscriber, ZEROMQ); 204 | lo_server s = lo_server_new("7772", error); 205 | 206 | lo_server_add_method(s, "/play", "iisffffffsffffififfffiffffi", 207 | play_handler, 208 | NULL 209 | ); 210 | 211 | lo_server_add_method(s, "/play", "iisffffffsffffififfffiffff", 212 | play_handler, 213 | NULL 214 | ); 215 | 216 | lo_server_add_method(s, "/play", "iisffffffsffffififfffifff", 217 | play_handler, 218 | NULL 219 | ); 220 | 221 | lo_server_add_method(s, "/play", "iisffffffsffffififff", 222 | play_handler, 223 | NULL 224 | ); 225 | 226 | lo_server_add_method(s, NULL, NULL, generic_handler, NULL); 227 | 228 | assert(rc == 0); 229 | // Subscribe to all 230 | rc = zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, 231 | NULL, 0); 232 | assert (rc == 0); 233 | while(1) { 234 | int size = zmq_recv(subscriber, buffer, MAXOSCSZ, 0); 235 | if (size > 0) { 236 | lo_server_dispatch_data(s, buffer, size); 237 | } 238 | else { 239 | printf("oops.\n"); 240 | } 241 | } 242 | return(NULL); 243 | } 244 | #endif 245 | 246 | /**/ 247 | 248 | extern int server_init(const char *osc_port) { 249 | 250 | lo_server_thread st = lo_server_thread_new(osc_port, error); 251 | 252 | lo_server_thread_add_method(st, "/play", NULL, play_handler, NULL); 253 | 254 | lo_server_thread_add_method(st, NULL, NULL, generic_handler, NULL); 255 | lo_server_thread_start(st); 256 | 257 | 258 | #ifdef ZEROMQ 259 | pthread_t t; 260 | pthread_create(&t, NULL, (void *(*)(void *)) zmqthread, NULL); 261 | #endif 262 | 263 | return(1); 264 | } 265 | 266 | extern void osc_send_pitch(double starttime, unsigned int chunk, 267 | float pitch, float flux, float centroid) { 268 | static lo_address t = NULL; 269 | static int pid = 0; 270 | if (t == NULL) { 271 | t = lo_address_new(NULL, "6010"); 272 | } 273 | if (pid == 0) { 274 | pid = (int) getpid(); 275 | } 276 | //printf("send [%d] %f\n", chunk, pitch); 277 | // pid, starttime, chunk, v_pitch, v_flux, v_centroid 278 | lo_send(t, "/chunk", "ififff", 279 | pid, 280 | starttime, 281 | (int) chunk, 282 | pitch, 283 | flux, 284 | centroid 285 | ); 286 | 287 | } 288 | 289 | extern void osc_send_play(double when, int lowchunk, float pitch, float flux, float centroid) { 290 | static lo_address t = NULL; 291 | static int pid = 0; 292 | if (t == NULL) { 293 | t = lo_address_new(NULL, "6010"); 294 | } 295 | if (pid == 0) { 296 | pid = (int) getpid(); 297 | } 298 | printf("play [%d] %f\n", lowchunk, pitch); 299 | // pid, starttime, chunk, v_pitch, v_flux, v_centroid 300 | lo_send(t, "/play", "iiiifff", 301 | pid, 302 | (int) when, 303 | (int) ((when - floor(when)) * 1000000.0f), 304 | lowchunk, 305 | pitch, 306 | flux, 307 | centroid 308 | ); 309 | 310 | } 311 | 312 | -------------------------------------------------------------------------------- /server.h: -------------------------------------------------------------------------------- 1 | extern int server_init(const char *osc_port); 2 | extern void osc_send_pitch(double starttime, unsigned int chunk, 3 | float pitch, float flux, float centroid); 4 | extern void osc_send_play(double when, int lowchunk, float pitch, float flux, float centroid); 5 | -------------------------------------------------------------------------------- /thpool.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "thpool.h" 6 | 7 | static void* thread_do(void* p); 8 | 9 | struct thpool { 10 | pthread_t* threads; 11 | jobqueue_t* queue; 12 | unsigned int num_threads; 13 | 14 | pthread_mutex_t update_mutex; 15 | pthread_cond_t update_cv; 16 | 17 | bool running; 18 | }; 19 | 20 | thpool_t* thpool_init(unsigned int num_threads) { 21 | thpool_t* p = malloc(sizeof(thpool_t)); 22 | if (!p) return NULL; 23 | 24 | p->threads = malloc(sizeof(pthread_t) * num_threads); 25 | if (!p->threads) return NULL; 26 | 27 | p->queue = jobqueue_init(); 28 | 29 | pthread_mutex_init(&p->update_mutex, NULL); 30 | pthread_cond_init(&p->update_cv, NULL); 31 | 32 | p->num_threads = num_threads; 33 | p->running = true; 34 | 35 | // Initialize and detach threads 36 | for (unsigned int i = 0; i < num_threads; i++) { 37 | int rc = pthread_create(&p->threads[i], NULL, thread_do, p); 38 | if (rc) return NULL; 39 | pthread_detach(p->threads[i]); 40 | } 41 | 42 | return p; 43 | } 44 | 45 | bool thpool_add_job(thpool_t* p, void *(*function)(void*), void* args) { 46 | bool res = jobqueue_push(p->queue, JOB(function, args)); 47 | 48 | if (res) { 49 | pthread_mutex_lock(&p->update_mutex); 50 | pthread_cond_broadcast(&p->update_cv); 51 | pthread_mutex_unlock(&p->update_mutex); 52 | } 53 | 54 | return res; 55 | } 56 | 57 | unsigned int thpool_size(const thpool_t* p) { 58 | return p->num_threads; 59 | } 60 | 61 | void thpool_destroy(thpool_t* p) { 62 | p->running = false; 63 | 64 | pthread_mutex_lock(&p->update_mutex); 65 | pthread_cond_broadcast(&p->update_cv); 66 | pthread_mutex_unlock(&p->update_mutex); 67 | 68 | // TODO: Wait for threads to destroy themselves, somehow 69 | // ... 70 | 71 | free(p->threads); 72 | jobqueue_destroy(p->queue); 73 | 74 | pthread_mutex_destroy(&p->update_mutex); 75 | pthread_cond_destroy(&p->update_cv); 76 | 77 | free(p); 78 | } 79 | 80 | 81 | static void* thread_do(void *arg) { 82 | thpool_t* p = arg; 83 | job_t j; 84 | 85 | while (true) { 86 | while (p->running && jobqueue_pop(p->queue, &j)) { 87 | j.function(j.args); 88 | } 89 | 90 | if (!p->running) break; 91 | 92 | pthread_mutex_lock(&p->update_mutex); 93 | pthread_cond_wait(&p->update_cv, &p->update_mutex); 94 | pthread_mutex_unlock(&p->update_mutex); 95 | } 96 | 97 | pthread_exit(NULL); 98 | } 99 | -------------------------------------------------------------------------------- /thpool.h: -------------------------------------------------------------------------------- 1 | #ifndef __THPOOL_H__ 2 | #define __THPOOL_H__ 3 | 4 | #include 5 | 6 | #include "jobqueue.h" 7 | 8 | typedef struct thpool thpool_t; 9 | 10 | // Initialize a thread pool of a specified size 11 | thpool_t* thpool_init(unsigned int num_threads); 12 | 13 | // Push a job to the queue 14 | bool thpool_add_job(thpool_t* p, void *(*function)(void*), void* args); 15 | 16 | // Return the size (number of threads) a pool has 17 | unsigned int thpool_size(const thpool_t* p); 18 | 19 | // De-allocated thread pool and its associated structures 20 | void thpool_destroy(thpool_t* p); 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /windows/dirt-pa.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tidalcycles/Dirt/4edc6192da3508fecb9f2e26bb0370cdeb6c4166/windows/dirt-pa.exe -------------------------------------------------------------------------------- /zmqserv.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAXSZ 1024 7 | 8 | lo_server s; 9 | void *publisher; 10 | 11 | void error(int num, const char *msg, const char *path) { 12 | printf("liblo server error %d in path %s: %s\n", num, path, msg); 13 | } 14 | 15 | /**/ 16 | 17 | int generic_handler(const char *path, const char *types, lo_arg **argv, 18 | int argc, lo_message msg, void *user_data) { 19 | int i; 20 | int sz = lo_message_length(msg, path); 21 | void *m = lo_message_serialise(msg, path, NULL, NULL); 22 | printf("message\n"); 23 | zmq_send(publisher, m, sz, 0); 24 | free(m); 25 | return 1; 26 | } 27 | 28 | void osc_init() { 29 | s = lo_server_new("7777", error); 30 | lo_server_add_method(s, NULL, NULL, generic_handler, NULL); 31 | } 32 | 33 | int main (void) { 34 | // Prepare our context and publisher 35 | void *context = zmq_ctx_new (); 36 | publisher = zmq_socket (context, ZMQ_PUB); 37 | int rc = zmq_bind (publisher, "tcp://*:5556"); 38 | void *osc[MAXSZ]; 39 | 40 | assert (rc == 0); 41 | rc = zmq_bind(publisher, "ipc://dirt.ipc"); 42 | assert (rc == 0); 43 | 44 | osc_init(); 45 | 46 | while (1) { 47 | int sz = lo_server_recv(s); 48 | //printf("processed message of size %d\n", sz); 49 | } 50 | zmq_close (publisher); 51 | zmq_ctx_destroy (context); 52 | return 0; 53 | } 54 | 55 | --------------------------------------------------------------------------------