packages feed

synthesizer-alsa (empty) → 0.5.0.6

raw patch · 15 files changed

Files

+ LICENSE view
@@ -0,0 +1,674 @@+                    GNU GENERAL PUBLIC LICENSE+                       Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++                            Preamble++  The GNU General Public License is a free, copyleft license for+software and other kinds of works.++  The licenses for most software and other practical works are designed+to take away your freedom to share and change the works.  By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.  We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors.  You can apply it to+your programs, too.++  When we speak of free software, we are referring to freedom, not+price.  Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++  To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights.  Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++  For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received.  You must make sure that they, too, receive+or can get the source code.  And you must show them these terms so they+know their rights.++  Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++  For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software.  For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++  Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so.  This is fundamentally incompatible with the aim of+protecting users' freedom to change the software.  The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable.  Therefore, we+have designed this version of the GPL to prohibit the practice for those+products.  If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++  Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary.  To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++  The precise terms and conditions for copying, distribution and+modification follow.++                       TERMS AND CONDITIONS++  0. Definitions.++  "This License" refers to version 3 of the GNU General Public License.++  "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++  "The Program" refers to any copyrightable work licensed under this+License.  Each licensee is addressed as "you".  "Licensees" and+"recipients" may be individuals or organizations.++  To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy.  The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++  A "covered work" means either the unmodified Program or a work based+on the Program.++  To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy.  Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++  To "convey" a work means any kind of propagation that enables other+parties to make or receive copies.  Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++  An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License.  If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++  1. Source Code.++  The "source code" for a work means the preferred form of the work+for making modifications to it.  "Object code" means any non-source+form of a work.++  A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++  The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form.  A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++  The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities.  However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work.  For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++  The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++  The Corresponding Source for a work in source code form is that+same work.++  2. Basic Permissions.++  All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met.  This License explicitly affirms your unlimited+permission to run the unmodified Program.  The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work.  This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++  You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force.  You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright.  Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++  Conveying under any other circumstances is permitted solely under+the conditions stated below.  Sublicensing is not allowed; section 10+makes it unnecessary.++  3. Protecting Users' Legal Rights From Anti-Circumvention Law.++  No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++  When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++  4. Conveying Verbatim Copies.++  You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++  You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++  5. Conveying Modified Source Versions.++  You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++    a) The work must carry prominent notices stating that you modified+    it, and giving a relevant date.++    b) The work must carry prominent notices stating that it is+    released under this License and any conditions added under section+    7.  This requirement modifies the requirement in section 4 to+    "keep intact all notices".++    c) You must license the entire work, as a whole, under this+    License to anyone who comes into possession of a copy.  This+    License will therefore apply, along with any applicable section 7+    additional terms, to the whole of the work, and all its parts,+    regardless of how they are packaged.  This License gives no+    permission to license the work in any other way, but it does not+    invalidate such permission if you have separately received it.++    d) If the work has interactive user interfaces, each must display+    Appropriate Legal Notices; however, if the Program has interactive+    interfaces that do not display Appropriate Legal Notices, your+    work need not make them do so.++  A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit.  Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++  6. Conveying Non-Source Forms.++  You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++    a) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by the+    Corresponding Source fixed on a durable physical medium+    customarily used for software interchange.++    b) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by a+    written offer, valid for at least three years and valid for as+    long as you offer spare parts or customer support for that product+    model, to give anyone who possesses the object code either (1) a+    copy of the Corresponding Source for all the software in the+    product that is covered by this License, on a durable physical+    medium customarily used for software interchange, for a price no+    more than your reasonable cost of physically performing this+    conveying of source, or (2) access to copy the+    Corresponding Source from a network server at no charge.++    c) Convey individual copies of the object code with a copy of the+    written offer to provide the Corresponding Source.  This+    alternative is allowed only occasionally and noncommercially, and+    only if you received the object code with such an offer, in accord+    with subsection 6b.++    d) Convey the object code by offering access from a designated+    place (gratis or for a charge), and offer equivalent access to the+    Corresponding Source in the same way through the same place at no+    further charge.  You need not require recipients to copy the+    Corresponding Source along with the object code.  If the place to+    copy the object code is a network server, the Corresponding Source+    may be on a different server (operated by you or a third party)+    that supports equivalent copying facilities, provided you maintain+    clear directions next to the object code saying where to find the+    Corresponding Source.  Regardless of what server hosts the+    Corresponding Source, you remain obligated to ensure that it is+    available for as long as needed to satisfy these requirements.++    e) Convey the object code using peer-to-peer transmission, provided+    you inform other peers where the object code and Corresponding+    Source of the work are being offered to the general public at no+    charge under subsection 6d.++  A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++  A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling.  In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage.  For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product.  A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++  "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source.  The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++  If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information.  But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++  The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed.  Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++  Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++  7. Additional Terms.++  "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law.  If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++  When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it.  (Additional permissions may be written to require their own+removal in certain cases when you modify the work.)  You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++  Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++    a) Disclaiming warranty or limiting liability differently from the+    terms of sections 15 and 16 of this License; or++    b) Requiring preservation of specified reasonable legal notices or+    author attributions in that material or in the Appropriate Legal+    Notices displayed by works containing it; or++    c) Prohibiting misrepresentation of the origin of that material, or+    requiring that modified versions of such material be marked in+    reasonable ways as different from the original version; or++    d) Limiting the use for publicity purposes of names of licensors or+    authors of the material; or++    e) Declining to grant rights under trademark law for use of some+    trade names, trademarks, or service marks; or++    f) Requiring indemnification of licensors and authors of that+    material by anyone who conveys the material (or modified versions of+    it) with contractual assumptions of liability to the recipient, for+    any liability that these contractual assumptions directly impose on+    those licensors and authors.++  All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10.  If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term.  If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++  If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++  Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++  8. Termination.++  You may not propagate or modify a covered work except as expressly+provided under this License.  Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++  However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++  Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++  Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License.  If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++  9. Acceptance Not Required for Having Copies.++  You are not required to accept this License in order to receive or+run a copy of the Program.  Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance.  However,+nothing other than this License grants you permission to propagate or+modify any covered work.  These actions infringe copyright if you do+not accept this License.  Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++  10. Automatic Licensing of Downstream Recipients.++  Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License.  You are not responsible+for enforcing compliance by third parties with this License.++  An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations.  If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++  You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License.  For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++  11. Patents.++  A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based.  The+work thus licensed is called the contributor's "contributor version".++  A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version.  For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++  Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++  In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement).  To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++  If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients.  "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++  If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++  A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License.  You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++  Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++  12. No Surrender of Others' Freedom.++  If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License.  If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all.  For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++  13. Use with the GNU Affero General Public License.++  Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work.  The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++  14. Revised Versions of this License.++  The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time.  Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++  Each version is given a distinguishing version number.  If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation.  If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++  If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++  Later license versions may give you additional or different+permissions.  However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++  15. Disclaimer of Warranty.++  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++  16. Limitation of Liability.++  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++  17. Interpretation of Sections 15 and 16.++  If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++                     END OF TERMS AND CONDITIONS++            How to Apply These Terms to Your New Programs++  If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++  To do so, attach the following notices to the program.  It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++    <one line to give the program's name and a brief idea of what it does.>+    Copyright (C) <year>  <name of author>++    This program is free software: you can redistribute it and/or modify+    it under the terms of the GNU General Public License as published by+    the Free Software Foundation, either version 3 of the License, or+    (at your option) any later version.++    This program is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU General Public License for more details.++    You should have received a copy of the GNU General Public License+    along with this program.  If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++  If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++    <program>  Copyright (C) <year>  <name of author>+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+    This is free software, and you are welcome to redistribute it+    under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License.  Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++  You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<http://www.gnu.org/licenses/>.++  The GNU General Public License does not permit incorporating your program+into proprietary programs.  If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library.  If this is what you want to do, use the GNU Lesser General+Public License instead of this License.  But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+ Setup.lhs view
@@ -0,0 +1,3 @@+#! /usr/bin/env runhaskell+> import Distribution.Simple+> main = defaultMain
+ server/Synthesizer/ALSA/Dimensional/Server.hs view
@@ -0,0 +1,18 @@+module Main where++import qualified Synthesizer.ALSA.Dimensional.Server.Run  as Run+import qualified Synthesizer.ALSA.Dimensional.Server.Test as Test++main :: IO ()+main =+   case fromInteger 106 :: Int of+      001 -> Test.sequence1+      100 -> Run.volume+      101 -> Run.pitchBend+      102 -> Run.volumePitchBend1+      103 -> Run.keyboard+      104 -> Run.keyboardMulti+      105 -> Run.keyboardFM+      106 -> Run.keyboardDetuneFM+      107 -> Run.keyboardFilter+      _ -> error "not implemented"
+ server/Synthesizer/ALSA/Dimensional/Server/Common.hs view
@@ -0,0 +1,101 @@+{-# LANGUAGE RebindableSyntax #-}+{-# LANGUAGE RankNTypes #-}+module Synthesizer.ALSA.Dimensional.Server.Common where++import qualified Synthesizer.ALSA.Dimensional.Play as Play++import qualified Sound.ALSA.PCM as ALSA+import qualified Sound.ALSA.Sequencer.Event as Event++import qualified Synthesizer.ALSA.EventList as MIDIEv++import qualified Synthesizer.ALSA.Storable.Play as PlaySt++import qualified Synthesizer.Dimensional.Rate.Filter as FiltR+import qualified Synthesizer.Dimensional.Process as Proc++import Synthesizer.Dimensional.Process (($:), )++import qualified Data.StorableVector.Lazy         as SVL++import qualified Sound.MIDI.Message.Channel       as ChannelMsg++import qualified Data.EventList.Relative.TimeBody  as EventList++-- import qualified Numeric.NonNegative.Class   as NonNeg+-- import qualified Numeric.NonNegative.Wrapper as NonNegW+-- import qualified Numeric.NonNegative.ChunkyPrivate as NonNegChunky++import qualified Algebra.Module         as Module+import qualified Algebra.RealField      as RealField+import qualified Algebra.Field          as Field+import qualified Algebra.Ring           as Ring++import qualified Algebra.DimensionTerm as Dim+import qualified Number.DimensionTerm  as DN++import NumericPrelude.Numeric+import NumericPrelude.Base hiding (break, )++++channel :: ChannelMsg.Channel+channel = ChannelMsg.toChannel 0+++sampleRate :: Ring.C a => DN.Frequency a+-- sampleRate = DN.frequency 48000+sampleRate = DN.frequency 44100++latency :: Field.C a => DN.Time a+latency = DN.time 0+-- latency = DN.time 0.01++{-+chunkSize :: SVL.ChunkSize+chunkSize = Play.defaultChunkSize+-}++periodTime :: Field.C a => DN.Time a+periodTime =+   let (SVL.ChunkSize size) = PlaySt.defaultChunkSize+   in  DN.scale (fromIntegral size) $ DN.unrecip sampleRate++device :: Play.Device+device = PlaySt.defaultDevice++clientName :: MIDIEv.ClientName+clientName = MIDIEv.ClientName "Haskell-Synthesizer"+++type Real = Double+++{-# INLINE withMIDIEvents #-}+withMIDIEvents ::+   Field.C t =>+   (DN.Time t -> DN.Frequency t ->+    (forall s. Proc.T s Dim.Time t+        (Play.StorableSignal s Dim.Voltage y yv)) ->+    IO b) ->+   (EventList.T MIDIEv.StrictTime [Event.T] ->+    forall s. Proc.T s Dim.Time t+       (Play.StorableSignal s Dim.Voltage y yv)) ->+   IO b+withMIDIEvents action proc =+   MIDIEv.withMIDIEvents clientName+      (DN.toNumberWithDimension Dim.time periodTime :: Double)+      (DN.toNumberWithDimension Dim.frequency sampleRate :: Double) $+   \ sig -> action periodTime sampleRate (proc sig)++{-# INLINE play #-}+play ::+   (Module.C y yv, ALSA.SampleFmt yv, RealField.C t) =>+   DN.Time t ->+   DN.Frequency t ->+   (forall s. Proc.T s Dim.Time t+      (Play.StorableSignal s Dim.Voltage y yv)) ->+   IO ()+play period rate sig =+   Play.renderTimeVoltageStorable device period rate+   (FiltR.delay latency $: sig)
+ server/Synthesizer/ALSA/Dimensional/Server/Run.hs view
@@ -0,0 +1,186 @@+{-# LANGUAGE RebindableSyntax #-}+module Synthesizer.ALSA.Dimensional.Server.Run where++import Synthesizer.ALSA.Dimensional.Server.Common+import qualified Synthesizer.MIDI.Dimensional.Example.Instrument as Instr++import qualified Synthesizer.MIDI.Dimensional as MIDI++import qualified Synthesizer.ALSA.Storable.Play as PlaySt++import qualified Synthesizer.Dimensional.Causal.Process    as Causal+import qualified Synthesizer.Dimensional.Causal.Oscillator as Osci+import qualified Synthesizer.Dimensional.Causal.Filter     as Filt+import qualified Synthesizer.Dimensional.Causal.FilterParameter   as FiltP+import qualified Synthesizer.Dimensional.Causal.ControlledProcess as CProc++import qualified Synthesizer.Dimensional.Rate.Oscillator as OsciR+import qualified Synthesizer.Dimensional.Amplitude.Control as CtrlA+import qualified Synthesizer.Dimensional.Amplitude.Displacement as DispA+import qualified Synthesizer.Dimensional.Amplitude.Filter as FiltA+import qualified Synthesizer.Dimensional.Signal.Private as SigA+import qualified Synthesizer.Dimensional.Wave as WaveD++import Synthesizer.Dimensional.Causal.Process ((<<<), )+import Synthesizer.Dimensional.Wave ((&*~), )+import Synthesizer.Dimensional.Process (($:), (.:), )+import Control.Applicative (liftA2, liftA3, (<$>), )++import qualified Synthesizer.Basic.Wave          as Wave++import qualified Sound.MIDI.Message.Channel.Voice as VoiceMsg++import qualified Number.DimensionTerm  as DN++import NumericPrelude.Numeric+import NumericPrelude.Base hiding (break, )++++channelVolume :: VoiceMsg.Controller+channelVolume = VoiceMsg.modulation+++volume :: IO ()+volume =+   putStrLn "run 'aconnect' to connect to the MIDI controller" >>+   (withMIDIEvents play $+   \evs ->+      liftA3+          (\env osci vol ->+              Causal.apply+                 (Causal.applySnd env osci) $+              MIDI.piecewiseConstant $ vol)+          Filt.envelopeScalarDimension+          (OsciR.static (DN.voltage 1 &*~ Wave.sine) zero (DN.frequency (880::Real)))+          (MIDI.runFilter evs (MIDI.controllerLinear channel channelVolume+              (DN.scalar 0, DN.scalar 1) (DN.scalar (1::Real)))))++pitchBend :: IO ()+pitchBend =+   withMIDIEvents play $+   \evs ->+      liftA2 Causal.apply+          (Osci.freqMod (DN.voltage (1::Real) &*~ Wave.sine) zero)+          (MIDI.piecewiseConstant <$>+           MIDI.runFilter evs+              (MIDI.pitchBend channel 2 (DN.frequency (880::Real))))++-- preserve chunk structure of channel volume+volumePitchBend0 :: IO ()+volumePitchBend0 =+   putStrLn "run 'aconnect' to connect to the MIDI controller" >>+   (withMIDIEvents play $+   \evs ->+      liftA3+          (\osci env (freq,vol) ->+              Causal.apply+                 (Causal.applySnd env (osci $ SigA.restore freq)) $+                 MIDI.piecewiseConstant vol)+          (OsciR.freqMod (DN.voltage 1 &*~ Wave.sine) zero)+          Filt.envelopeScalarDimension+          (MIDI.runFilter evs $ liftA2 (,)+             (MIDI.pitchBend channel 2 (DN.frequency (880::Real)))+             (MIDI.controllerLinear channel channelVolume+                (DN.scalar 0, DN.scalar 1) (DN.scalar (1::Real)))))++-- preserve chunk structure of pitch bender+volumePitchBend1 :: IO ()+volumePitchBend1 =+   putStrLn "run 'aconnect' to connect to the MIDI controller" >>+   (withMIDIEvents play $+   \evs ->+      liftA3+          (\osci env (freq,vol) ->+              Causal.apply+                 (Causal.applyFst env (SigA.restore vol) <<< osci) $+                 MIDI.piecewiseConstant freq)+          (Osci.freqMod (DN.voltage 1 &*~ Wave.sine) zero)+          Filt.envelopeScalarDimension+          (MIDI.runFilter evs $ liftA2 (,)+             (MIDI.pitchBend channel 2 (DN.frequency (880::Real)))+             (MIDI.controllerLinear channel channelVolume+                (DN.scalar 0, DN.scalar 1) (DN.scalar (1::Real)))))+++keyboard :: IO ()+keyboard =+   withMIDIEvents play $+   \evs ->+      MIDI.runFilter evs+         (MIDI.sequence PlaySt.defaultChunkSize (DN.voltage 1) channel Instr.ping)+++keyboardMulti :: IO ()+keyboardMulti =+   withMIDIEvents play $+   \evs ->+      MIDI.runFilter evs+         (MIDI.sequenceMultiProgram PlaySt.defaultChunkSize (DN.voltage 1) channel+             (VoiceMsg.toProgram 0)+             [Instr.ping, Instr.pingRelease])+--             [Instr.string])+++keyboardFM :: IO ()+keyboardFM =+   withMIDIEvents play $+   \evs ->+      FiltA.amplify 0.3 <$>+         (MIDI.runFilter evs+            (MIDI.sequenceModulated PlaySt.defaultChunkSize (DN.voltage 1) channel Instr.pingReleaseFM $:+             MIDI.bendWheelPressure channel 2 (DN.frequency 10) 0.04 0.03))+--             MIDI.pitchBend channel (2 ** recip 12) (DN.scalar one)))+++extraController :: VoiceMsg.Controller+extraController =+   VoiceMsg.vectorX+--   VoiceMsg.toController 21++extraController1 :: VoiceMsg.Controller+extraController1 =+   VoiceMsg.modulation+--   VoiceMsg.vectorY+--   VoiceMsg.toController 22+++keyboardDetuneFM :: IO ()+keyboardDetuneFM =+   withMIDIEvents play $+   \evs ->+      FiltA.amplify 0.3 <$>+         (MIDI.runFilter evs+            (MIDI.sequenceMultiModulated PlaySt.defaultChunkSize (DN.voltage 1) channel Instr.pingStereoDetuneFM+              ((MIDI.applyModulation <$>+                  MIDI.bendWheelPressure channel 2 (DN.frequency 10) 0.04 0.03)+               .:+               (MIDI.applyModulation <$>+                  MIDI.controllerLinear channel extraController (0, 0.005) 0))+               ))+++keyboardFilter :: IO ()+keyboardFilter =+   withMIDIEvents play $+   \evs ->+        liftA3+           (\osci filt (music,speed,depth) ->+              (FiltP.lowpassFromUniversal <<<+               filt (CtrlA.constant 10)+                 (DispA.mapExponential 4 (DN.frequency 1000) $+                  FiltA.envelope (SigA.restore depth) $+                  osci (SigA.restore speed)))+              `Causal.apply`+              FiltA.amplify 0.2 music)+           (OsciR.freqMod (WaveD.flat Wave.sine) zero)+           (CProc.runSynchronous2 FiltP.universal)+--           FiltR.universal+           (MIDI.runFilter evs+              (liftA3 (,,)+                 (MIDI.sequence PlaySt.defaultChunkSize (DN.voltage 1) channel Instr.string)+                 (MIDI.controllerExponential channel extraController+                     (DN.frequency 0.1, DN.frequency 5) (DN.frequency 0.2))+                 (MIDI.controllerLinear channel extraController1+                     (0, 1 :: DN.Scalar Real) 0.5)+            ))
+ server/Synthesizer/ALSA/Dimensional/Server/Test.hs view
@@ -0,0 +1,58 @@+{-# LANGUAGE RebindableSyntax #-}+{-# LANGUAGE Rank2Types #-}+module Synthesizer.ALSA.Dimensional.Server.Test where++import Synthesizer.ALSA.Dimensional.Server.Common+import Synthesizer.MIDI.Dimensional.Example.Instrument (ping, )++import qualified Synthesizer.ALSA.Storable.Play as PlaySt++import qualified Synthesizer.MIDI.Dimensional as MIDI+import qualified Synthesizer.MIDI.EventList as MIDIEv+import qualified Synthesizer.MIDI.Generic as MidiG++import qualified Synthesizer.Dimensional.Signal.Private as SigA+import qualified Synthesizer.Dimensional.Process as Proc++import qualified Synthesizer.Storable.Signal      as SigSt+import qualified Data.StorableVector.Lazy         as SVL++import qualified Data.EventList.Relative.TimeBody  as EventList++import qualified Sound.ALSA.Sequencer.Event as Event++import qualified Algebra.DimensionTerm as Dim+import qualified Number.DimensionTerm  as DN++import NumericPrelude.Numeric+import NumericPrelude.Base hiding (break, )++++sequence1 :: IO ()+sequence1 =+--   print =<<+--   File.renderTimeVoltageMonoDoubleToInt16 sampleRate "test.wav"+   SVL.writeFile "test.f32"+      (SigA.scalarSamples (DN.toNumberWithDimension Dim.voltage)+      (SigA.render sampleRate+         (let evs t = EventList.cons t ([]::[Event.T]) (evs (20-t))+              {-+              evs0 =+                 EventList.cons 10 [makeNote AlsaMidi.NoteOn 60] $+                 EventList.cons 10 [makeNote AlsaMidi.NoteOn 64] $+                 evs 10+              -}+          in  MIDI.runFilter (evs 10)+                 (MIDI.sequence PlaySt.defaultChunkSize+                    (DN.voltage 1) channel ping))))++sequence2 ::+   EventList.T MIDIEv.StrictTime [SigSt.T Real]+sequence2 =+   fmap (map SigA.body) $+   flip Proc.process sampleRate+      (let evs t = EventList.cons t ([]::[Event.T]) (evs (20-t))+       in  MIDI.runFilter (evs 10)+              (MIDI.prepareTones channel MidiG.errorNoProgram+                 (const ping)))
+ server/Synthesizer/ALSA/Storable/Server.hs view
@@ -0,0 +1,113 @@+module Main where++import qualified Synthesizer.ALSA.Storable.Server.Run as Run+import qualified Synthesizer.ALSA.Storable.Server.Test as Test+import Synthesizer.ALSA.Storable.Server.Common+          (Real, play, sampleRate, chunkSize, periodTime, )++import qualified Synthesizer.Basic.Wave          as Wave++import qualified Synthesizer.ALSA.Storable.Play as Play+import qualified Synthesizer.Storable.Oscillator  as OsciSt+import qualified Synthesizer.Storable.Signal      as SigSt+import qualified Data.StorableVector.Lazy as SVL++import NumericPrelude.Numeric (zero, )+import Prelude hiding (Real, break, id, (.), )+++{-+This program has still a very slowly growing memory leak.+-}+main :: IO ()+main =+   case fromInteger 300 :: Int of+      001 -> print Test.keyboard3+      002 -> play (periodTime::Real) sampleRate Test.keyboard3+      003 -> Test.speed+      004 -> Test.frequency1+      005 -> Test.frequency2+      006 -> Test.frequency3+{-+      007 -> Test.frequency4+-}+      008 -> Test.keyboard1+      009 -> SigSt.writeFile "test.f32" Test.keyboard2+      010 -> SigSt.writeFile "test.f32" Test.keyboard3+      011 -> SigSt.writeFile "test.f32" Test.keyboard4+      012 -> SigSt.writeFile "test.f32" Test.keyboard5+{-+      013 -> Test.keyboard6+      014 -> Test.keyboard7+-}+      015 -> Test.arrangeSpaceLeak0+      016 -> Test.arrangeSpaceLeak1+      018 -> Test.arrangeSpaceLeak3+      019 -> Test.arrangeSpaceLeak4+      020 -> Test.chordSpaceLeak1+--      021 -> Test.chordSpaceLeak2+--      022 -> Test.chordSpaceLeak3+--      023 -> Test.chordSpaceLeak4+      023 -> Test.sequencePitchBend+      024 -> Test.sequencePitchBend1+      025 -> Test.sequencePitchBend2+      026 -> Test.sequencePitchBend3+      027 -> Test.sequencePitchBend4+      028 -> Test.sequencePitchBend4a+      029 -> Test.sequencePitchBend4b+      030 -> Test.sequencePitchBend4c+      031 -> Test.sequencePitchBend4d+      032 -> Test.sequencePitchBend4e+      033 -> Test.sequencePitchBend5+      040 -> Test.sequenceStaccato+      050 -> Test.speed+      051 -> Test.speedChunky+      052 -> Test.speedArrange+      053 -> Play.auto+{-+                (ALSA.alsaSoundSinkTime Play.defaultDevice+                    (ALSA.SoundFmt {+                       ALSA.sampleFreq = sampleRate+                    }) $+                 ALSA.SoundBufferTime+                    (round (5000000*periodTime::Real))+                    (round (1000000*periodTime::Real))+                ) $+-}+{-+                (ALSA.fileSoundSink "test.f32"+                   (ALSA.SoundFmt {+                      ALSA.sampleFreq = sampleRate+                   })) $+-}+                (Play.makeSink Play.defaultDevice (periodTime::Real) sampleRate) $+             SVL.cycle $+             SigSt.take 100000 $+                OsciSt.static chunkSize (fmap (0.9*) Wave.sine) zero (1/100::Real)+      054 -> Play.auto+                (Play.makeSink Play.defaultDevice (periodTime::Real) sampleRate) $+                OsciSt.static chunkSize (fmap (0.9*) Wave.sine)+                   zero (600/sampleRate::Real)+      055 -> play (periodTime::Real) sampleRate $+                OsciSt.static chunkSize (fmap (0.9*) Wave.sine)+                   zero (600/sampleRate::Real)+      100 -> Run.volume+      101 -> Run.frequency+      102 -> Run.frequencyCausal+      103 -> Run.pitchBend+      104 -> Run.volumeFrequency+      105 -> Run.volumeFrequencyCausal+      200 -> Run.keyboard+      201 -> Run.keyboardMulti+      202 -> Run.keyboardStereo+      203 -> Run.keyboardPitchbend+      204 -> Run.keyboardFM+      205 -> Run.keyboardDetuneFM+      206 -> Run.keyboardFilter+      207 -> Run.keyboardSample+      208 -> Run.keyboardVariousStereo+      209 -> Run.keyboardSampleTFM+      210 -> Run.keyboardNoisyTone+      211 -> Run.keyboardFilteredNoisyTone+      300 -> Run.keyboardCausal+      _   -> error "not implemented server part"
+ server/Synthesizer/ALSA/Storable/Server/Common.hs view
@@ -0,0 +1,101 @@+module Synthesizer.ALSA.Storable.Server.Common where++import qualified Sound.ALSA.PCM as ALSA+import qualified Sound.ALSA.Sequencer.Event as Event++import qualified Synthesizer.ALSA.Storable.Play as Play+import qualified Synthesizer.ALSA.EventList as MIDIEv+import Synthesizer.ALSA.EventList (StrictTime, )++import qualified Synthesizer.Generic.Signal       as SigG+import qualified Synthesizer.Storable.Signal      as SigSt+import qualified Data.StorableVector.Lazy         as SVL++import qualified Sound.MIDI.Message.Channel       as ChannelMsg+import Sound.MIDI.Message.Channel (Channel, )++import qualified Data.EventList.Relative.TimeBody  as EventList++import qualified Sound.Sox.Frame         as SoxFrame+import qualified System.Exit as Exit++import Control.Category ((.), )++import qualified Algebra.RealField as RealField+import qualified Algebra.Field     as Field+import qualified Algebra.Ring      as Ring+import qualified Algebra.ToInteger as ToInteger+import qualified Algebra.Additive  as Additive++import NumericPrelude.Numeric (zero, round, )+import Prelude hiding (Real, round, break, id, (.), )+++channel :: Channel+channel = ChannelMsg.toChannel 0++sampleRate :: Num a => a+-- sampleRate = 24000+-- sampleRate = 48000+sampleRate = 44100++latency :: Int+latency = 0+-- latency = 256+-- latency = 1000++chunkSize :: SVL.ChunkSize+chunkSize = Play.defaultChunkSize++lazySize :: SigG.LazySize+lazySize =+   let (SVL.ChunkSize size) = chunkSize+   in  SigG.LazySize size++periodTime :: Field.C t => t+periodTime =+   let (SVL.ChunkSize size) = chunkSize+   in  ToInteger.fromIntegral size Field./ Ring.fromInteger sampleRate++device :: Play.Device+device = Play.defaultDevice++clientName :: MIDIEv.ClientName+clientName = MIDIEv.ClientName "Haskell-Synthesizer"+++type Real = Float+++{-# INLINE withMIDIEvents #-}+withMIDIEvents ::+   (Double -> Double -> a -> IO b) ->+   (EventList.T StrictTime [Event.T] -> a) -> IO b+withMIDIEvents action proc =+   let rate = sampleRate+       per  = periodTime+   in  MIDIEv.withMIDIEvents clientName per rate $+       action per rate . proc+++{-# INLINE play #-}+play ::+   (RealField.C t, Additive.C y, ALSA.SampleFmt y) =>+   t -> t -> SigSt.T y -> IO ()+play period rate =+   Play.auto (Play.makeSink device period (round rate)) .+   SigSt.append (SigSt.replicate chunkSize latency zero)+--   FiltG.delayPosLazySize chunkSize latency+--   FiltG.delayPos latency++-- ToDo: do not record the empty chunk that is inserted for latency+{-# INLINE playAndRecord #-}+playAndRecord ::+   (RealField.C t, Additive.C y, ALSA.SampleFmt y, SoxFrame.C y) =>+   FilePath -> t -> t -> SigSt.T y -> IO Exit.ExitCode+playAndRecord fileName period rate =+   let intRate = round rate+   in  Play.autoAndRecord fileName+          (ALSA.SoundFmt {ALSA.sampleFreq = intRate})+          (Play.makeSink device period intRate) .+       SigSt.append (SigSt.replicate chunkSize latency zero)
+ server/Synthesizer/ALSA/Storable/Server/Run.hs view
@@ -0,0 +1,335 @@+module Synthesizer.ALSA.Storable.Server.Run where++import qualified Synthesizer.MIDI.Example.Instrument as Instr+import Synthesizer.ALSA.Storable.Server.Common+          (Real, withMIDIEvents, play, device, clientName,+           sampleRate, lazySize, chunkSize, periodTime, channel, )++import qualified Synthesizer.MIDI.CausalIO.Process as MIO+import qualified Synthesizer.MIDI.Storable as MidiSt+import Synthesizer.MIDI.Storable (applyModulation, )++import qualified Synthesizer.ALSA.CausalIO.Process as PAlsa+import qualified Synthesizer.CausalIO.Process as PIO++import qualified Synthesizer.Causal.Oscillator as OsciC+import qualified Synthesizer.Causal.Process as Causal+import qualified Synthesizer.Causal.Filter.NonRecursive as FiltNRC++import qualified Synthesizer.Basic.Wave          as Wave++import qualified Synthesizer.Interpolation.Module as Ip++import qualified Synthesizer.Storable.Oscillator  as OsciSt+import qualified Synthesizer.Storable.Signal      as SigSt+import qualified Data.StorableVector.Lazy         as SVL+import qualified Data.StorableVector              as SV+import Foreign.Storable (Storable, )++import qualified Synthesizer.Generic.Loop      as LoopG+import qualified Synthesizer.Generic.Signal    as SigG+import qualified Synthesizer.State.Signal      as SigS+import qualified Synthesizer.Plain.Filter.Recursive    as FiltR+import qualified Synthesizer.Plain.Filter.Recursive.Universal as UniFilter++import qualified Sound.MIDI.Message.Channel.Voice as VoiceMsg++import Control.Monad.Trans.State (evalState, )+import Control.Category ((.), )+import Control.Arrow (arr, second, (&&&), )++import Data.Tuple.HT (mapSnd, )++import NumericPrelude.Numeric+import NumericPrelude.Base hiding ((.), )+import Prelude ()++++volume :: IO ()+volume =+   putStrLn "run 'aconnect' to connect to the MIDI controller" >>+   (withMIDIEvents play $+      SigSt.zipWith (*)+         (OsciSt.static chunkSize Wave.sine zero (800/sampleRate)) .+      evalState (MidiSt.controllerLinear channel VoiceMsg.mainVolume (0,1) (0.2::Real)))++frequency :: IO ()+frequency =+   withMIDIEvents play $+      OsciSt.freqMod chunkSize Wave.sine zero .+      evalState (MidiSt.controllerExponential channel VoiceMsg.modulation+         (400/sampleRate, 1600/sampleRate) (800/sampleRate::Real))+++{-# INLINE storableChunk #-}+storableChunk ::+   (SigG.Read sig a, Storable a) =>+   sig a -> SV.Vector a+storableChunk chunk =+   SigS.toStrictStorableSignal (SigG.length chunk) $+   SigG.toState chunk++frequencyCausal :: IO ()+frequencyCausal =+   PAlsa.playFromEvents device clientName 0.01 (periodTime::Double) sampleRate+      ((PIO.fromCausal $+        Causal.applyStorableChunk $+        OsciC.freqMod (fmap (0.99*) Wave.sine) zero)+       .+       arr storableChunk+       .+       (MIO.controllerExponential channel VoiceMsg.modulation+          (400/sampleRate, 1600/sampleRate) (800/sampleRate::Real)))+++pitchBend :: IO ()+pitchBend =+   withMIDIEvents play $+      OsciSt.freqMod chunkSize Wave.sine zero .+      evalState (MidiSt.pitchBend channel 2 (880/sampleRate::Real))++volumeFrequency :: IO ()+volumeFrequency =+   putStrLn "run 'aconnect' to connect to the MIDI controller" >>+   (withMIDIEvents play $+      evalState (do+         vol  <- MidiSt.controllerLinear channel VoiceMsg.mainVolume (0,1) 0.5+         freq <- MidiSt.pitchBend channel 2 (880/sampleRate::Real)+         return $+            SigSt.zipWith (*) vol+               (OsciSt.freqMod chunkSize Wave.sine zero freq)))++volumeFrequencyCausal :: IO ()+volumeFrequencyCausal =+   PAlsa.playFromEvents device clientName 0.01 (periodTime::Double) sampleRate+      ((PIO.fromCausal $+        Causal.applyStorableChunk $+        FiltNRC.envelope+        .+        second (OsciC.freqMod Wave.sine zero))+       .+       arr (uncurry (SV.zipWith (,)))+       .+       (arr storableChunk+        .+        MIO.controllerLinear channel VoiceMsg.mainVolume (0,0.99) (0.5::Real)+        &&&+        arr storableChunk+        .+        MIO.pitchBend channel 2 (880/sampleRate::Real)))+++keyboard :: IO ()+keyboard =+   withMIDIEvents play $+--      playALSA (Bld.put :: Int16 -> Bld.Builder Int16) (sampleRate::Real) .+      SigSt.map (0.2*) .+      evalState (MidiSt.sequence chunkSize channel Instr.tine)++keyboardMulti :: IO ()+keyboardMulti =+   withMIDIEvents play $+--      playALSA (Bld.put :: Int16 -> Bld.Builder Int16) (sampleRate::Real) .+      SigSt.map (0.2*) .+      evalState (MidiSt.sequenceMultiProgram chunkSize channel+         (VoiceMsg.toProgram 2)+         [Instr.pingDur, Instr.pingRelease, Instr.tine])++keyboardStereo :: IO ()+keyboardStereo =+   withMIDIEvents play $+--      playALSA (Bld.put :: Int16 -> Bld.Builder Int16) (sampleRate::Real) .+      SigSt.map ((0.2::Real)*>) .+      evalState (MidiSt.sequenceMultiProgram chunkSize channel+         (VoiceMsg.toProgram 1)+         [Instr.pingStereoRelease, Instr.tineStereo,+          Instr.softString, Instr.softStringCausal])++keyboardPitchbend :: IO ()+keyboardPitchbend =+   withMIDIEvents play $+      SigSt.map ((0.2::Real)*>) .+      evalState+         (do bend <- MidiSt.pitchBend channel (2^?(2/12)) 1+             MidiSt.sequenceModulated chunkSize bend channel Instr.stringStereoFM)++keyboardFM :: IO ()+keyboardFM =+   withMIDIEvents play $+      SigSt.map ((0.2::Real)*>) .+      evalState+         (do fm <- MidiSt.bendWheelPressure channel+                      2 (10/sampleRate) 0.04 0.03+             MidiSt.sequenceModulated chunkSize fm channel Instr.stringStereoFM)++keyboardDetuneFM :: IO ()+keyboardDetuneFM =+   withMIDIEvents play $+      SigSt.map ((0.2::Real)*>) .+      evalState+         (do fm <- MidiSt.bendWheelPressure channel+                      2 (10/sampleRate) 0.04 0.03+             detune <- MidiSt.controllerLinear channel+                          VoiceMsg.vectorX (0,0.005) 0+             MidiSt.sequenceMultiModulated+                chunkSize channel Instr.stringStereoDetuneFM+                (applyModulation fm .+                 applyModulation detune))+++keyboardFilter :: IO ()+keyboardFilter =+   withMIDIEvents play $+      SigSt.map (0.2*) .+      evalState+         (do music <- MidiSt.sequence chunkSize channel Instr.pingRelease+             freq  <- MidiSt.controllerLinear channel+                         -- VoiceMsg.vectorY+                         (VoiceMsg.toController 21)+                         (100/sampleRate, 5000/sampleRate)+                         (700/sampleRate)+             return $+                SigS.toStorableSignal chunkSize $+                SigS.map UniFilter.lowpass $+                SigS.modifyModulated+                   UniFilter.modifier+                   (SigS.map UniFilter.parameter $+                    SigS.zipWith FiltR.Pole+                       (SigS.repeat (5 :: Real))+                       (SigS.fromStorableSignal freq)) $+                SigS.fromStorableSignal music)+++makeLoop ::+   LoopG.TimeControl Real -> Real -> Real ->+   (Real, SigSt.T Real) -> (Real, SigSt.T Real)+makeLoop = LoopG.timeReverse lazySize Ip.linear Ip.linear++keyboardSample :: IO ()+keyboardSample =+   do piano <- Instr.readPianoSample+      string <- Instr.readStringSample+      let loopedString     = mapSnd (LoopG.simple 8750 500) string+          fadedString      = mapSnd (LoopG.fade (undefined::Real) 8750 500) string+          timeSineString   = makeLoop LoopG.timeControlSine 8750 500 string+          timeZigZagString = makeLoop LoopG.timeControlZigZag 8750 500 string+      withMIDIEvents play $+         SigSt.map (0.2*) .+         evalState (MidiSt.sequenceMultiProgram chunkSize channel+               (VoiceMsg.toProgram 5) $+            Instr.sampledSound piano :+            Instr.sampledSound string :+            Instr.sampledSound loopedString :+            Instr.sampledSound fadedString :+            Instr.sampledSound timeSineString :+            Instr.sampledSound timeZigZagString :+            Instr.sampledSoundTimeLoop Instr.loopTimeModSine string 8750 500 :+            Instr.sampledSoundTimeLoop Instr.loopTimeModZigZag string 8750 500 :+            [])+++keyboardVariousStereo :: IO ()+keyboardVariousStereo =+   do piano <- Instr.readPianoSample+      string <- Instr.readStringSample+      let loopedString = makeLoop LoopG.timeControlZigZag 8750 500 string+      withMIDIEvents play $+         SigSt.map ((0.2::Real)*>) .+         evalState (MidiSt.sequenceMultiProgram chunkSize channel+               (VoiceMsg.toProgram 0) $+            Instr.pingStereoRelease :+            Instr.tineStereo :+            Instr.softString :+            Instr.sampledSoundDetuneStereo 0.001 piano :+            Instr.sampledSoundDetuneStereo 0.002 loopedString :+            Instr.sampledSoundDetuneStereoRelease 0.1 0.001 piano :+            Instr.sampledSoundDetuneStereoRelease 0.3 0.002 loopedString :+            [])+++keyboardSampleTFM :: IO ()+keyboardSampleTFM =+   do instr <- Instr.readPianoSample+      withMIDIEvents play $+         evalState+            (do fm <- MidiSt.bendWheelPressure channel+                         2 (10/sampleRate) 0.04 0.03+                speed <- MidiSt.controllerLinear channel+                             (VoiceMsg.toController 22)+                             (0,2) 1+                offset <- MidiSt.controllerLinear channel+                             (VoiceMsg.toController 21)+                             (0, fromIntegral (SVL.length (snd instr))) 0+                MidiSt.sequenceMultiModulated+                   chunkSize channel (Instr.timeModulatedSample instr)+                   (applyModulation fm .+                    applyModulation speed .+                    applyModulation offset))+++keyboardNoisePipe :: IO ()+keyboardNoisePipe =+   withMIDIEvents play $+      evalState+         (do fm <- MidiSt.bendWheelPressure channel+                      2 (10/sampleRate) 0.04 0.03+             resonance <-+                   MidiSt.controllerExponential channel+                      (VoiceMsg.toController 23)+                      (1, 100) 10+             MidiSt.sequenceMultiModulated+                chunkSize channel Instr.colourNoise+                (applyModulation fm .+                 applyModulation resonance))+++keyboardNoisyTone :: IO ()+keyboardNoisyTone =+   withMIDIEvents play $+      evalState+         (do fm <- MidiSt.bendWheelPressure channel+                      2 (10/sampleRate) 0.04 0.03+             speed <- MidiSt.controllerLinear channel+                          (VoiceMsg.toController 21)+                          (0,0.5) 0.1+             MidiSt.sequenceMultiModulated+                chunkSize channel Instr.toneFromNoise+                (applyModulation fm .+                 applyModulation speed))+++keyboardFilteredNoisyTone :: IO ()+keyboardFilteredNoisyTone =+   withMIDIEvents play $+      evalState+         (do fm <- MidiSt.bendWheelPressure channel+                      2 (10/sampleRate) 0.04 0.03+             {-+             speed must never be zero,+             since this requires to fetch unlimited data from future.+             -}+             speed <- MidiSt.controllerLinear channel+                          (VoiceMsg.toController 21)+                          (0.05,0.5) 0.1+             cutoff <- MidiSt.controllerExponential channel+                          (VoiceMsg.toController 22)+                          (1, 30) 10+             resonance <- MidiSt.controllerExponential channel+                          (VoiceMsg.toController 23)+                          (1, 20) 5+             MidiSt.sequenceMultiModulated+                chunkSize channel Instr.toneFromFilteredNoise+                (applyModulation fm .+                 applyModulation speed .+                 applyModulation cutoff .+                 applyModulation resonance))++++keyboardCausal :: IO ()+keyboardCausal =+   PAlsa.playFromEvents device clientName 0.01 (periodTime::Double) sampleRate $+      arr (SV.map (0.2*))+      .+      MIO.sequenceStorable channel (\ _pgm -> Instr.pingReleaseCausal)
+ server/Synthesizer/ALSA/Storable/Server/Test.hs view
@@ -0,0 +1,582 @@+module Synthesizer.ALSA.Storable.Server.Test where++import qualified Synthesizer.MIDI.Example.Instrument as Instr+import Synthesizer.ALSA.Storable.Server.Common+          (Real, withMIDIEvents, play,+           sampleRate, chunkSize, channel, )++import qualified Sound.ALSA.Sequencer.Address as Addr+import qualified Sound.ALSA.Sequencer.Event as Event++import qualified Synthesizer.MIDI.PiecewiseConstant as PC+import qualified Synthesizer.MIDI.Generic as Gen+import qualified Synthesizer.MIDI.Storable as MidiSt+import Synthesizer.MIDI.Storable (+   Instrument, chunkSizesFromLazyTime, )++import qualified Synthesizer.MIDI.EventList as MIDIEv+import Synthesizer.MIDI.EventList (+   LazyTime, StrictTime, Note(..), NoteBoundary(..),+   matchNoteEvents, getSlice, getControllerEvents, )++import qualified Synthesizer.Basic.Wave          as Wave++import qualified Synthesizer.Causal.Process as Causal+import Control.Arrow ((<<<), )++import qualified Synthesizer.Storable.Cut         as CutSt+import qualified Synthesizer.Storable.Oscillator  as OsciSt+import qualified Synthesizer.Storable.Signal      as SigSt+-- import qualified Data.StorableVector.Lazy.Builder as Bld+import qualified Data.StorableVector.Lazy.Pattern as SigStV+import qualified Data.StorableVector.Lazy         as SVL+import qualified Data.StorableVector              as SV++import qualified Synthesizer.State.Signal      as SigS++import qualified Sound.MIDI.Message.Channel.Voice as VoiceMsg+import Sound.MIDI.Message.Channel.Voice (normalVelocity, )++import qualified Data.EventList.Relative.TimeBody  as EventList+import qualified Data.EventList.Relative.BodyTime  as EventListBT+import Data.EventList.Relative.MixedBody ((/.), (./), )++import qualified Control.Monad.Trans.State.Strict as MS+import Control.Monad.Trans.State (evalState, gets, )+import Control.Category ((.), )++import Data.Traversable (traverse, )++-- import qualified Numeric.NonNegative.Class   as NonNeg+import qualified Numeric.NonNegative.Wrapper as NonNegW+import qualified Numeric.NonNegative.Chunky as NonNegChunky++import Data.Maybe.HT (toMaybe, )++import NumericPrelude.Numeric (zero, round, (^?), )+import Prelude hiding (Real, round, break, id, (.), )++++frequency1 :: IO ()+frequency1 =+   withMIDIEvents play $+      const+        (OsciSt.static chunkSize Wave.sine zero (800/sampleRate::Real))++frequency2 :: IO ()+frequency2 =+   withMIDIEvents (const $ const print) $+      evalState (getControllerEvents channel VoiceMsg.mainVolume)++frequency3 :: IO ()+frequency3 =+   withMIDIEvents (const $ const print) $+      evalState (getSlice Just)+++keyboard1 :: IO ()+keyboard1 =+   withMIDIEvents play $+      const (Instr.ping 0 440)++keyboard2 :: SigSt.T Real+keyboard2 =+   let music :: Real -> EventList.T StrictTime (SigSt.T Real)+       music x = 5 /. SigSt.replicate chunkSize 6 x ./ music (x+1)+   in  CutSt.arrange chunkSize $+       EventList.mapTime fromIntegral $ music 42++keyboard3 :: SigSt.T Real+keyboard3 =+   let time :: Real -> Int+       time t = round (t * sampleRate)+       music :: Real -> EventList.T StrictTime (SigSt.T Real)+       music x =+          fromIntegral (time 0.2) /.+          SigSt.take (time 0.4) (Instr.ping 0 x) ./+          music (x*1.01)+   in  CutSt.arrange chunkSize $+       EventList.mapTime fromIntegral $ music 110++makeLazyTime :: Real -> LazyTime+makeLazyTime t =+   NonNegChunky.fromNumber $+   NonNegW.fromNumberMsg "keyboard time" $+   round (t * sampleRate)++makeStrictTime :: Real -> StrictTime+makeStrictTime t =+   NonNegW.fromNumberMsg "keyboard time" $+   round (t * sampleRate)++pitch :: Int -> VoiceMsg.Pitch+pitch = VoiceMsg.toPitch++defaultProgram :: VoiceMsg.Program+defaultProgram = VoiceMsg.toProgram 0++embedDefaultProgram ::+   EventList.T StrictTime [NoteBoundary Bool] ->+   EventList.T StrictTime [NoteBoundary (Maybe VoiceMsg.Program)]+embedDefaultProgram =+   fmap (fmap (\(NoteBoundary p v b) ->+      NoteBoundary p v (toMaybe b defaultProgram)))++keyboard4 :: SigSt.T Real+keyboard4 =+   let {-+       idInstr :: Real -> Real -> SigSt.T Real+       idInstr _vel freq = SigSt.repeat chunkSize freq+       -}+--       inf = time 0.4 + inf+       music :: Int -> EventList.T StrictTime Note+       music p =+          makeStrictTime 0.2 /.+--          (pitch p, normalVelocity, inf) ./+          Note defaultProgram (pitch p) normalVelocity (makeLazyTime 0.4) ./+          music (p+1)+   in  CutSt.arrange chunkSize $+       EventList.mapTime fromIntegral $+       fmap (Gen.renderInstrumentIgnoreProgram Instr.pingDur) $+       music 0+++notes0 :: Int -> EventList.T StrictTime (NoteBoundary Bool)+notes0 p =+   makeStrictTime 0.2 /.+   (let (oct,pc) = divMod p 12+    in  (NoteBoundary (pitch (50 + pc)) normalVelocity (even oct)))+      ./+   notes0 (p+1)++notes1 :: EventList.T StrictTime (NoteBoundary Bool)+notes1 =+   makeStrictTime 0.2 /.+   (NoteBoundary (pitch 50) normalVelocity True) ./+   makeStrictTime 0.2 /.+   (NoteBoundary (pitch 52) normalVelocity True) ./+   makeStrictTime 0.2 /.+   (NoteBoundary (pitch 54) normalVelocity True) ./+   makeStrictTime 0.2 /.+--   (NoteBoundary (pitch 50) normalVelocity False) ./+   undefined++notes2 :: EventList.T StrictTime [NoteBoundary Bool]+notes2 =+   makeStrictTime 0.2 /.+   [] ./+   makeStrictTime 0.2 /.+   [] ./+   makeStrictTime 0.2 /.+   [NoteBoundary (pitch 50) normalVelocity True] ./+   makeStrictTime 0.2 /.+   [NoteBoundary (pitch 52) normalVelocity True] ./+   makeStrictTime 0.2 /.+   [NoteBoundary (pitch 54) normalVelocity True] ./+   makeStrictTime 0.2 /.+   [NoteBoundary (pitch 50) normalVelocity False] ./+   undefined++notes3 :: EventList.T StrictTime [NoteBoundary (Maybe VoiceMsg.Program)]+notes3 =+   embedDefaultProgram $+   notes2++keyboard5 :: SigSt.T Real+keyboard5 =+   CutSt.arrange chunkSize $+   EventList.mapTime fromIntegral $+   Gen.flatten $+   fmap (map (Gen.renderInstrumentIgnoreProgram Instr.pingDur)) $+   matchNoteEvents $+   notes3++keyboard6 :: EventList.T StrictTime [Note]+keyboard6 =+   matchNoteEvents $+   embedDefaultProgram $+   fmap (:[]) $+   notes1++keyboard7 :: EventList.T StrictTime [(VoiceMsg.Pitch, VoiceMsg.Velocity)]+keyboard7 =+   fmap (map (\ ~(Note _ p v _d) -> (p,v))) $+   keyboard6+++emptyEvents :: StrictTime -> EventList.T StrictTime [Event.T]+emptyEvents time =+   let evs = EventList.cons time [] evs+   in  evs+++arrangeSpaceLeak0 :: IO ()+arrangeSpaceLeak0 =+   SVL.writeFile "test.f32" $+   CutSt.arrange chunkSize $+   evalState (Gen.sequence channel+      (error "no sound" :: Instrument Real Real)) $+   emptyEvents 10++arrangeSpaceLeak1 :: IO ()+arrangeSpaceLeak1 =+   SVL.writeFile "test.f32" $+   CutSt.arrange chunkSize $+   evalState+      (Gen.sequenceModulated+         (SigSt.iterate chunkSize (1+) 0) channel+         (error "no sound" :: SigSt.T Real -> Instrument Real Real)) $+   emptyEvents 10++makeNote :: Event.NoteEv -> Event.Pitch -> Event.T+makeNote typ pit =+   Event.simple Addr.subscribers $ Event.NoteEv typ $+   Event.simpleNote (Event.Channel 0) pit Event.normalVelocity++{-+a space leak can only be observed for more than one note,+maybe our 'break' improvement fixed the case for one played note+-}+arrangeSpaceLeak3 :: IO ()+arrangeSpaceLeak3 =+   SVL.writeFile "test.f32" $+   CutSt.arrange chunkSize $+   evalState+      (Gen.sequenceModulated+         (SigSt.iterate chunkSize (1e-7 +) 1) channel+         Instr.stringStereoFM) $+--         (const Instr.pingDur :: SigSt.T Real -> Instrument Real Real)) $+   let evs t = EventList.cons t ([]::[Event.T]) (evs (20-t))+   in  -- EventList.cons 10 [makeNote MIDI.NoteOn 60] $+       -- EventList.cons 10 [makeNote MIDI.NoteOn 64] $+       evs 10++arrangeSpaceLeak4 :: IO ()+arrangeSpaceLeak4 =+   SVL.writeFile "test.f32" $+   evalState+      (do bend <- MidiSt.pitchBend channel (2^?(2/12)) 1+          MidiSt.sequenceModulated chunkSize bend channel Instr.stringStereoFM) $+   let evs t = EventList.cons t ([]::[Event.T]) (evs (20-t))+   in  evs 10++chordSpaceLeak1 :: IO ()+chordSpaceLeak1 =+   SVL.writeFile "test.f32" $+   CutSt.arrange chunkSize $+   evalState (Gen.sequence channel Instr.pingDur) $+   let evs t = EventList.cons t [] (evs (20-t))+   in  EventList.cons 10 [makeNote Event.NoteOn $ Event.Pitch 60] $+       EventList.cons 10 [makeNote Event.NoteOn $ Event.Pitch 64] $+       evs 10+++sequencePitchBend :: IO ()+sequencePitchBend =+   SVL.writeFile "test.f32" $+      CutSt.arrange chunkSize $+      evalState+         (let fm y = (EventListBT.cons $! y) 10 (fm (2-y))+          in  Gen.sequenceModulated (fm 1) channel+                 (error "no sound" ::+                     PC.T Real -> Instrument Real Real)) $+      emptyEvents 10++sequencePitchBend1 :: IO ()+sequencePitchBend1 =+   SVL.writeFile "test.f32" $+      CutSt.arrange chunkSize $+      evalState+         (let fm y = EventListBT.cons y 10 (fm (2-y))+              instr :: PC.T Real -> Instrument Real Real+              instr = error "no sound"+          in  Gen.sequenceCore+                 channel Gen.errorNoProgram+                 (Gen.Modulator (fm 1) Gen.advanceModulationChunk+                     (\note -> gets $ \c ->+                         Gen.renderInstrumentIgnoreProgram (instr c) note))) $+      emptyEvents 10++sequencePitchBend2 :: IO ()+sequencePitchBend2 =+   SVL.writeFile "test.f32" $+      let fm y = EventListBT.cons y 10 (fm (2-y))+          -- fm = EventListBT.cons 1 10 fm+          instr :: PC.T Real -> Instrument Real Real+          instr = error "no sound"+          evs = EventList.cons 10 [] evs+          md =+             Gen.Modulator+                (fm 1)+                Gen.advanceModulationChunkPC+                -- Gen.advanceModulationChunk+                (\note -> gets $ \c ->+                    Gen.renderInstrumentIgnoreProgram (instr c) note)+      in  CutSt.arrange chunkSize .+          EventList.mapTime fromIntegral .+          Gen.flatten .+          Gen.applyModulator md $+          evs++sequencePitchBend3 :: IO ()+sequencePitchBend3 =+   SVL.writeFile "test.f32" $+      let fm y = EventListBT.cons y 10 (fm (2-y))+          -- fm = EventListBT.cons 1 10 fm+          instr :: PC.T Real -> Instrument Real Real+          instr = error "no sound"+          evs = EventList.cons 10 [] evs+          modEvent note =+             gets $ \c ->+                Gen.renderInstrumentIgnoreProgram (instr c) note+      in  CutSt.arrange chunkSize .+          EventList.mapTime fromIntegral .+          Gen.flatten .+          flip evalState (fm 1) .+          EventList.traverse+             Gen.advanceModulationChunk+             (traverse modEvent) $+          evs++sequencePitchBend4 :: IO ()+sequencePitchBend4 =+   SVL.writeFile "test.f32" $+      let fm y = y : fm (2-y)+          -- fm = repeat 1+          instr :: [Real] -> Instrument Real Real+          instr = error "no sound"+          evs = EventList.cons 10 [] evs+          modEvent note =+             gets $ \c ->+                Gen.renderInstrumentIgnoreProgram (instr c) note+      in  CutSt.arrange chunkSize .+          EventList.mapTime fromIntegral .+          Gen.flatten .+          flip evalState (fm 1) .+          EventList.traverse+             Gen.advanceModulationChunk+             (traverse modEvent) $+          evs++sequencePitchBend4a :: IO ()+sequencePitchBend4a =+   SVL.writeFile "test.f32" $+      let fm y = y : fm (2-y)+          -- fm = repeat 1+          instr :: [Real] -> Instrument Real Real+          instr = error "no sound"+          evs = EventList.cons 10 [] evs+          modEvent note =+             MS.gets $ \c ->+                Gen.renderInstrumentIgnoreProgram (instr c) note+      in  CutSt.arrange chunkSize .+          EventList.mapTime fromIntegral .+          Gen.flatten .+          flip MS.evalState (fm 1) .+          EventList.traverse+             Gen.advanceModulationChunkStrict+             (traverse modEvent) $+          evs++sequencePitchBend4b :: IO ()+sequencePitchBend4b =+   SVL.writeFile "test.f32" $+      let fm y = y : fm (2-y)+          -- fm = repeat 1+          instr :: [Real] -> Instrument Real Real+          instr = error "no sound"+          evs = EventList.cons 10 [] evs+      in  CutSt.arrange chunkSize .+          Gen.flatten $+          EventList.foldrPair+             (\t bs0 go s0 ->+                let s1 = tail s0+                    bs1 =+                       map (Gen.renderInstrumentIgnoreProgram (instr s1)) bs0+                in  EventList.cons+                       (if null s1 then t else t) bs1 $+                    go s1)+             (const EventList.empty) evs (fm 1)++sequencePitchBend4c :: IO ()+sequencePitchBend4c =+   SVL.writeFile "test.f32" $+      let fm y = y : fm (2-y)+          -- fm = repeat 1+          instr :: [Real] -> Instrument Real Real+          instr = error "no sound"+      in  CutSt.arrange chunkSize .+          Gen.flatten .+          EventList.fromPairList $+          foldr+             (\(t,bs0) go s0 ->+                let s1 = tail s0+                    bs1 =+                       map (Gen.renderInstrumentIgnoreProgram (instr s1)) bs0+                in  (if null s1 then t else t, bs1) :+                    go s1)+             (const [])+             (repeat (10,[]))+             (fm 1)++sequencePitchBend4d :: IO ()+sequencePitchBend4d =+   SVL.writeFile "test.f32" $+      let fm y = y : fm (2-y)+          -- fm = repeat 1+      in  CutSt.arrange chunkSize .+          EventList.fromPairList $+          foldr+             (\(t,b) go s0 ->+                let s1 = tail s0+                in  (if null s1 then t else t,+                     if null s1 then b else b) :+                    go s1)+             (const [])+             (repeat (10, SigSt.empty :: SigSt.T Real))+             (fm 1 :: [Real])++sequencePitchBend4e :: IO ()+sequencePitchBend4e =+   writeFile "test.txt" $+   foldr+      (\c go s0 ->+         let s1 = tail s0+         in  (if null s1 then c else c) :+             go s1)+      (const [])+      (repeat 'a')+      (iterate not False)+      -- (repeat True)++sequencePitchBend5 :: IO ()+sequencePitchBend5 =+   SVL.writeFile "test.f32" $+      let fm y = SigSt.iterate (SVL.ChunkSize 1) (y+) 0+          instr :: SigSt.T Real -> Instrument Real Real+          instr = error "no sound"+          evs = EventList.cons 10 [] evs+          modEvent note =+             gets $ \c ->+                Gen.renderInstrumentIgnoreProgram (instr c) note+      in  CutSt.arrange chunkSize .+          EventList.mapTime fromIntegral .+          Gen.flatten .+          flip evalState (fm 1e-6) .+          EventList.traverse+             Gen.advanceModulationChunk+             (traverse modEvent) $+          evs++dummySound :: Instrument Real Real+dummySound =+   \vel freq dur ->+      SigStV.take (chunkSizesFromLazyTime dur) $+      SigSt.repeat chunkSize (vel + 1e-3*freq)++sequenceStaccato :: IO ()+sequenceStaccato =+   SVL.writeFile "test.f32" $+      let evs t =+             EventList.cons t [Right $ NoteBoundary (pitch 60) normalVelocity True] $+             EventList.cons t [Right $ NoteBoundary (pitch 60) normalVelocity False] $+             evs (20-t)+      in  CutSt.arrange chunkSize .+          EventList.mapTime fromIntegral .+          Gen.flatten .+          EventList.mapBody+             (map (Gen.renderInstrumentIgnoreProgram dummySound)) .+          MIDIEv.matchNoteEvents .+          MIDIEv.embedPrograms defaultProgram $+          evs 10++sequenceStaccato3 :: IO ()+sequenceStaccato3 =+   SVL.writeFile "test.f32" $+      let evs t =+             EventList.cons t [NoteBoundary (pitch 60) normalVelocity (Just defaultProgram)] $+             EventList.cons t [NoteBoundary (pitch 60) normalVelocity Nothing] $+             evs (20-t)+      in  CutSt.arrange chunkSize .+          EventList.mapTime fromIntegral .+          Gen.flatten .+          EventList.mapBody+             (map (Gen.renderInstrumentIgnoreProgram dummySound)) .+          MIDIEv.matchNoteEvents $+          evs 10++sequenceStaccato2 :: IO ()+sequenceStaccato2 =+   SVL.writeFile "test.f32" $+      let p = Event.Pitch 60+          evs t =+             EventList.cons t [makeNote Event.NoteOn  p] $+             EventList.cons t [makeNote Event.NoteOff p] $+             evs (20-t)+      in  CutSt.arrange chunkSize .+          EventList.mapTime fromIntegral .+          Gen.flatten .+          EventList.mapBody+             (map (Gen.renderInstrumentIgnoreProgram dummySound)) .+          MIDIEv.matchNoteEvents .+          MIDIEv.embedPrograms defaultProgram .+          evalState (MIDIEv.getNoteEvents channel) $+          evs 10++sequenceStaccato1 :: IO ()+sequenceStaccato1 =+   SVL.writeFile "test.f32" $+      CutSt.arrange chunkSize $+      evalState (Gen.sequence channel dummySound) $+      let p = Event.Pitch 60+          evs t =+             EventList.cons t [makeNote Event.NoteOn  p] $+             EventList.cons t [makeNote Event.NoteOff p] $+             evs (20-t)+      in  evs 10+++speed :: IO ()+speed =+   let _sig =+          Causal.apply+             (Instr.softStringCausalProcess 440 <<<+              Instr.softStringReleaseEnvelopeCausalProcess 0)+             (SigS.repeat True)+       sig =+          Causal.apply+             (Instr.softStringCausalProcess 440)+             (SigS.repeat 1)+   in  SV.writeFile "speed.f32" $+       SigS.runViewL sig+       (\next s -> fst $ SV.unfoldrN 1000000 next s)++speedChunky :: IO ()+speedChunky =+   let sig =+          Causal.apply+             (Instr.softStringCausalProcess 440 <<<+              Instr.softStringReleaseEnvelopeCausalProcess 0)+             (SigS.repeat True)+   in  SVL.writeFile "speed.f32" $+       SigSt.take 1000000 $+       SigS.toStorableSignal (SVL.chunkSize 100) sig+{-+       SigS.runViewL sig+       (\next s -> SVL.take 1000000 (SVL.unfoldr (SVL.chunkSize 100) next s))+-}++speedArrange :: IO ()+speedArrange =+   let sig =+          Causal.apply+             (Instr.softStringCausalProcess 440 <<<+              Instr.softStringReleaseEnvelopeCausalProcess 0)+             (SigS.repeat True)+       sigSt =+          SigS.toStorableSignal (SVL.chunkSize 100) sig+   in  SVL.writeFile "speed.f32" $+       SigSt.take 1000000 $+       CutSt.arrangeEquidist (SVL.chunkSize 100) $+       EventList.fromPairList [(10000,sigSt)]
+ src/Synthesizer/ALSA/CausalIO/Process.hs view
@@ -0,0 +1,96 @@+module Synthesizer.ALSA.CausalIO.Process (+   Events,+   playFromEvents,+   Output,+   playFromEventsWithParams,+   ) where++import qualified Synthesizer.ALSA.EventList as MIDIEv++import qualified Synthesizer.ALSA.Storable.Play as Play+import Synthesizer.MIDI.EventList (StrictTime, )++import qualified Synthesizer.CausalIO.Process as PIO++import qualified Sound.ALSA.PCM as PCM+import qualified Sound.ALSA.Sequencer.Event as Event++import qualified Data.EventList.Relative.TimeTime  as EventListTT++import qualified Algebra.RealField      as RealField+import qualified Algebra.Additive       as Additive++import qualified Data.StorableVector as SV++import Control.Exception (bracket, )++import NumericPrelude.Numeric+import NumericPrelude.Base+import Prelude ()+++type Events = EventListTT.T StrictTime [Event.T]++playFromEvents ::+   (RealField.C time, PCM.SampleFmt a, Additive.C a) =>+   Play.Device -> MIDIEv.ClientName -> time -> time -> PCM.SampleFreq ->+   PIO.T Events (SV.Vector a) ->+   IO ()+playFromEvents device name latency beat rate+      (PIO.Cons next create delete) =+   let sink = Play.makeSink device beat rate+       rateFloat = fromIntegral rate+   in  MIDIEv.withMIDIEventsChunked name beat rateFloat $ \getEventsList ->+       PCM.withSoundSink sink $ \to ->+{-+       Play.writeLazy sink to+          (SVL.replicate+              (SVL.chunkSize $ round (beat * rateFloat))+              (round (latency * rateFloat))+              (zero::Float))+-}+       Play.write sink to+          (SV.replicate (round (latency * rateFloat)) zero) >>+       (bracket create delete $ \state ->+        let loop getEvs0 s0 =+               case getEvs0 of+                  [] -> return ()+                  getEvents : getEvs1 -> do+                     evs <- getEvents+                     (pcm, s1) <- next evs s0+                     Play.write sink to pcm+                     loop getEvs1 s1+        in  loop getEventsList state)+++type Output handle signal a =+   (IO ((PCM.Size, PCM.SampleFreq), handle),+    handle -> IO (),+    handle -> signal -> IO a)++playFromEventsWithParams ::+   Output handle signal () ->+   MIDIEv.ClientName ->+   ((PCM.Size, PCM.SampleFreq) -> PIO.T Events signal) ->+   IO ()+playFromEventsWithParams (open, close, write) name process =+   bracket open (close . snd) $ \(p@(period,rate),h) ->+      let rateFloat = fromIntegral rate :: Double+          beat = fromIntegral period / rateFloat+      in  MIDIEv.withMIDIEventsChunked name beat rateFloat $ \getEventsList ->+             case process p of+                PIO.Cons next create delete -> do+{-+                   write+                      (SV.replicate (round (latency * rateFloat)) zero)+-}+                   bracket create delete $ \state ->+                      let loop getEvs0 s0 =+                             case getEvs0 of+                                [] -> return ()+                                getEvents : getEvs1 -> do+                                   evs <- getEvents+                                   (chunk, s1) <- next evs s0+                                   write h chunk+                                   loop getEvs1 s1+                      in  loop getEventsList state
+ src/Synthesizer/ALSA/Dimensional/Play.hs view
@@ -0,0 +1,123 @@+{-# LANGUAGE RebindableSyntax #-}+{-# LANGUAGE Rank2Types #-}+module Synthesizer.ALSA.Dimensional.Play where++import qualified Synthesizer.ALSA.Storable.Play as Play++import qualified Synthesizer.Dimensional.Rate as Rate+import qualified Synthesizer.Dimensional.Amplitude as Amp++import qualified Synthesizer.Dimensional.Process as Proc+import qualified Synthesizer.Dimensional.Signal.Private as SigA++import qualified Synthesizer.Frame.Stereo as Stereo++import qualified Synthesizer.Storable.Signal as SigSt++import qualified Sound.ALSA.PCM as ALSA++import qualified Algebra.DimensionTerm as Dim+import qualified Number.DimensionTerm  as DN++-- import qualified Algebra.ToInteger      as ToInteger+import qualified Algebra.Module         as Module+import qualified Algebra.RealRing      as RealRing+-- import qualified Algebra.Field          as Field+-- import qualified Algebra.Ring           as Ring++import Foreign.Storable (Storable, )++-- import NumericPrelude.Numeric+import NumericPrelude.Base+++type Device = String++type RenderedStorableSignal u t v y yv =+   SigA.T (Rate.Dimensional u t) (Amp.Dimensional v y) (SigSt.T yv)++type StorableSignal s v y yv =+   SigA.T (Rate.Phantom s) (Amp.Dimensional v y) (SigSt.T yv)+++makeSink ::+   (ALSA.SampleFmt y, RealRing.C t) =>+   Device {- ^ ALSA output device -} ->+   DN.Time t {- ^ period (buffer) size expressed in seconds -} ->+   DN.Frequency t {- ^ sample rate -} ->+   ALSA.SoundSink ALSA.Pcm y+makeSink device periodTime rate =+   Play.makeSink device+      (DN.toNumberWithDimension Dim.time periodTime)+      (RealRing.round (DN.toNumberWithDimension Dim.frequency rate))+++{-# INLINE timeVoltageStorable #-}+timeVoltageStorable ::+   (Module.C y yv, ALSA.SampleFmt yv, RealRing.C t) =>+   Device ->+   DN.Time t->+   RenderedStorableSignal Dim.Time t Dim.Voltage y yv ->+   IO ()+timeVoltageStorable device period sig =+   Play.auto (makeSink device period (SigA.actualSampleRate sig))+      (SigA.vectorSamples (DN.toNumberWithDimension Dim.voltage) sig)++{-# INLINE timeVoltageMonoStorableToInt16 #-}+timeVoltageMonoStorableToInt16 ::+   (Storable y, RealRing.C y, RealRing.C t) =>+   Device ->+   DN.Time t->+   RenderedStorableSignal Dim.Time t Dim.Voltage y y ->+   IO ()+timeVoltageMonoStorableToInt16 device period sig =+   Play.monoToInt16 (makeSink device period (SigA.actualSampleRate sig))+      (SigA.scalarSamples (DN.toNumberWithDimension Dim.voltage) sig)++{-# INLINE timeVoltageStereoStorableToInt16 #-}+timeVoltageStereoStorableToInt16 ::+   (Storable y, Module.C y y, RealRing.C y, RealRing.C t) =>+   Device ->+   DN.Time t->+   RenderedStorableSignal Dim.Time t Dim.Voltage y (Stereo.T y) ->+   IO ()+timeVoltageStereoStorableToInt16 device period sig =+   Play.stereoToInt16 (makeSink device period (SigA.actualSampleRate sig))+      (SigA.vectorSamples (DN.toNumberWithDimension Dim.voltage) sig)+++{-# INLINE renderTimeVoltageStorable #-}+renderTimeVoltageStorable ::+   (Module.C y yv, ALSA.SampleFmt yv, RealRing.C t) =>+   Device ->+   DN.Time t->+   DN.T Dim.Frequency t ->+   (forall s. Proc.T s Dim.Time t+      (StorableSignal s Dim.Voltage y yv)) ->+   IO ()+renderTimeVoltageStorable device period rate sig =+   timeVoltageStorable device period (SigA.render rate sig)++{-# INLINE renderTimeVoltageMonoStorableToInt16 #-}+renderTimeVoltageMonoStorableToInt16 ::+   (Storable y, RealRing.C y, RealRing.C t) =>+   Device ->+   DN.Time t->+   DN.T Dim.Frequency t ->+   (forall s. Proc.T s Dim.Time t+      (StorableSignal s Dim.Voltage y y)) ->+   IO ()+renderTimeVoltageMonoStorableToInt16 device period rate sig =+   timeVoltageMonoStorableToInt16 device period (SigA.render rate sig)++{-# INLINE renderTimeVoltageStereoStorableToInt16 #-}+renderTimeVoltageStereoStorableToInt16 ::+   (Storable y, Module.C y y, RealRing.C y, RealRing.C t) =>+   Device ->+   DN.Time t->+   DN.T Dim.Frequency t ->+   (forall s. Proc.T s Dim.Time t+      (StorableSignal s Dim.Voltage y (Stereo.T y))) ->+   IO ()+renderTimeVoltageStereoStorableToInt16 device period rate sig =+   timeVoltageStereoStorableToInt16 device period (SigA.render rate sig)
+ src/Synthesizer/ALSA/EventList.hs view
@@ -0,0 +1,505 @@+{-# LANGUAGE RebindableSyntax #-}+module Synthesizer.ALSA.EventList where++import qualified Sound.ALSA.Sequencer.Address as Addr+import qualified Sound.ALSA.Sequencer.Client as Client+import qualified Sound.ALSA.Sequencer.Port as Port+import qualified Sound.ALSA.Sequencer.Port.InfoMonad as PortInfo+import qualified Sound.ALSA.Sequencer.Event as Event+import qualified Sound.ALSA.Sequencer.Queue as Queue+import qualified Sound.ALSA.Sequencer.Time as Time+import qualified Sound.ALSA.Sequencer.RealTime as RealTime+import qualified Sound.ALSA.Sequencer as SndSeq+import qualified Sound.ALSA.Exception as AlsaExc++import qualified Data.EventList.Relative.TimeBody  as EventList+import qualified Data.EventList.Relative.TimeTime  as EventListTT+import qualified Data.EventList.Relative.MixedBody as EventListMB+import qualified Data.EventList.Relative.TimeMixed as EventListTM+import qualified Data.EventList.Absolute.TimeBody  as AbsEventList++import Sound.MIDI.ALSA.Construct ()+import Sound.MIDI.ALSA.Check ()+import Sound.MIDI.ALSA.Query ()++import System.IO.Unsafe (unsafeInterleaveIO, )+import Control.Concurrent (threadDelay)+import System.Time (ClockTime(TOD), getClockTime, )++import Control.Monad.Trans.State+          (evalState, modify, get, )++import qualified Numeric.NonNegative.Class   as NonNeg+import qualified Numeric.NonNegative.Wrapper as NonNegW++import qualified Algebra.RealField  as RealField+import qualified Algebra.Field      as Field++import Data.Tuple.HT (mapPair, mapSnd, )+import Data.Ord.HT (limit, )+import Control.Monad (liftM, liftM2, )++import NumericPrelude.Numeric+import NumericPrelude.Base+++{- |+The @time@ type needs high precision,+so you will certainly have to instantiate it with 'Double'.+'Float' has definitely not enough bits.+-}+getTimeSeconds :: Field.C time => IO time+getTimeSeconds =+   fmap clockTimeToSeconds getClockTime++clockTimeToSeconds :: Field.C time => ClockTime -> time+clockTimeToSeconds (TOD secs picos) =+   fromInteger secs + fromInteger picos * 1e-12++wait :: RealField.C time => time -> IO ()+wait t1 =+   do t0 <- getTimeSeconds+      threadDelay $ floor $ 1e6*(t1-t0)+++{-+We cannot easily turn this into a custom type,+since we need Maybe Event.T sometimes.+-}+type StampedEvent time = (time, Event.T)+++{- |+only use it for non-blocking sequencers++We ignore ALSA time stamps and use the time of fetching the event,+because I don't know whether the ALSA time stamps are in sync with getClockTime.+-}+getStampedEvent ::+   (Field.C time, SndSeq.AllowInput mode) =>+   SndSeq.T mode -> IO (StampedEvent time)+getStampedEvent h =+   liftM2 (,)+      getTimeSeconds+      (Event.input h)++{- | only use it for non-blocking sequencers -}+getWaitingStampedEvents ::+   (Field.C time, SndSeq.AllowInput mode) =>+   SndSeq.T mode -> IO [StampedEvent time]+getWaitingStampedEvents h =+   let loop =+          AlsaExc.catch+             (liftM2 (:) (getStampedEvent h) loop)+             (const $ return [])+   in  loop++{- |+RealTime.toFractional for NumericPrelude.+-}+realTimeToField :: (Field.C a) => RealTime.T -> a+realTimeToField (RealTime.Cons s n) =+   fromIntegral s + fromIntegral n / (10^9)++addStamp ::+   (RealField.C time) =>+   Event.T -> StampedEvent time+addStamp ev =+   (case Event.time ev of+      Time.Cons Time.Absolute (Time.Real t) -> realTimeToField t+      _ -> error "unsupported time stamp type",+    ev)++{- | only use it for blocking sequencers -}+getStampedEventsUntilTime ::+   (RealField.C time,+    SndSeq.AllowInput mode, SndSeq.AllowOutput mode) =>+   SndSeq.T mode ->+   Queue.T -> Port.T -> time ->+   IO [StampedEvent time]+getStampedEventsUntilTime h q p t =+   fmap (map addStamp) $ getEventsUntilTime h q p t+++{- |+The client id may differ from the receiving sequencer.+I do not know, whether there are circumstances, where this is useful.+-}+getEventsUntilEcho ::+   (SndSeq.AllowInput mode) =>+   Client.T -> SndSeq.T mode -> IO [Event.T]+getEventsUntilEcho c h =+   let loop = do+          ev <- Event.input h+          let abort =+                 case Event.body ev of+                    Event.CustomEv Event.Echo _ ->+                       c == Addr.client (Event.source ev)+                    _ -> False+          if abort+            then return []+            else liftM (ev:) loop+   in  loop++{- |+Get events until a certain point in time.+It sends itself an Echo event in order to measure time.+-}+getEventsUntilTime ::+   (RealField.C time,+    SndSeq.AllowInput mode, SndSeq.AllowOutput mode) =>+   SndSeq.T mode ->+   Queue.T -> Port.T -> time ->+   IO [Event.T]+getEventsUntilTime h q p t = do+   c <- Client.getId h+   _ <- Event.output h $+           makeEcho c q p t (Event.Custom 0 0 0)+   _ <- Event.drainOutput h+   getEventsUntilEcho c h+++getWaitingEvents ::+   (SndSeq.AllowInput mode) =>+   SndSeq.T mode -> IO [Event.T]+getWaitingEvents h =+   let loop =+          AlsaExc.catch+             (liftM2 (:) (Event.input h) loop)+             (const $ return [])+   in  loop++++type StrictTime = NonNegW.Integer+newtype ClientName = ClientName String+   deriving (Show)++{-+ghc -i:src -e 'withMIDIEvents 44100 print' src/Synthesizer/Storable/ALSA/MIDI.hs+-}+{-+Maybe it is better to not use type variable for sample rate,+because ALSA supports only integers,+and if ALSA sample rate and sample rate do not match due to rounding errors,+then play and event fetching get out of sync over the time.+-}+withMIDIEvents :: (RealField.C time) =>+   ClientName -> time -> time ->+   (EventList.T StrictTime [Event.T] -> IO a) -> IO a+withMIDIEvents =+   withMIDIEventsBlockEcho+++{-+as a quick hack, we neglect the ALSA time stamp and use getTime or so+-}+withMIDIEventsNonblockWaitGrouped :: (RealField.C time) =>+   ClientName -> time -> time ->+   (EventList.T StrictTime [Event.T] -> IO a) -> IO a+withMIDIEventsNonblockWaitGrouped name beat rate proc =+   withInPort name SndSeq.Nonblock $ \ h _p ->+   do start <- getTimeSeconds+      l <- lazySequence $+              flip map (iterate (beat+) start) $ \t ->+                 wait t >>+                 liftM+                    (\evs -> (t, evs))+                    (getWaitingEvents h)+{-+                 liftM2 (,)+                    getTimeSeconds+                    (getWaitingEvents h)+-}+      proc $+         discretizeTime rate $+         AbsEventList.fromPairList l++{-+With this function latency becomes longer and longer if xruns occur,+but the latency is not just adapted,+but ones xruns occur, this implies more and more xruns.+-}+withMIDIEventsNonblockWaitDefer :: (RealField.C time) =>+   ClientName -> time -> time ->+   (EventList.T StrictTime (Maybe Event.T) -> IO a) -> IO a+withMIDIEventsNonblockWaitDefer name beat rate proc =+   withInPort name SndSeq.Nonblock $ \ h _p ->+   do start <- getTimeSeconds+      l <- lazySequence $+              flip map (iterate (beat+) start) $ \t ->+                 wait t >>+                 liftM+                    (\ es -> (t, Nothing) : map (mapSnd Just) es)+                    (getWaitingStampedEvents h)+      proc $+         discretizeTime rate $+         {-+         delay events that are in wrong order+         disadvantage: we cannot guarantee a beat with a minimal period+         -}+         flip evalState start $+         AbsEventList.mapTimeM (\t -> modify (max t) >> get) $+         AbsEventList.fromPairList $ concat l++{-+We risk and endless skipping when the beat is too short.+(Or debug output slows down processing.)+-}+withMIDIEventsNonblockWaitSkip :: (RealField.C time) =>+   ClientName -> time -> time ->+   (EventList.T StrictTime (Maybe Event.T) -> IO a) -> IO a+withMIDIEventsNonblockWaitSkip name beat rate proc =+   withInPort name SndSeq.Nonblock $ \ h _p ->+   do start <- getTimeSeconds+      l <- lazySequence $+           flip map (iterate (beat+) start) $ \t ->+              do wait t+                 t0 <- getTimeSeconds+                 -- print (t-start,t0-start)+                 es <-+                    if t0>=t+beat+                      then return []+                      else getWaitingStampedEvents h+                 return $+                    (t0, Nothing) :+                    map (mapSnd Just) es+      proc $+         discretizeTime rate $+         AbsEventList.fromPairList $ concat l++withMIDIEventsNonblockWaitMin :: (RealField.C time) =>+   ClientName -> time -> time ->+   (EventList.T StrictTime (Maybe Event.T) -> IO a) -> IO a+withMIDIEventsNonblockWaitMin name beat rate proc =+   withInPort name SndSeq.Nonblock $ \ h _p ->+   do start <- getTimeSeconds+      l <- lazySequence $+              flip map (iterate (beat+) start) $ \t ->+                 wait t >>+                 liftM+                    (\ es ->+                       (minimum $ t : map fst es, Nothing) :+                       map (mapSnd Just) es)+                    (getWaitingStampedEvents h)+{-+      mapM_ print $ EventList.toPairList $+         discretizeTime rate $+         AbsEventList.fromPairList $ concat l+      proc undefined+-}+      proc $+         discretizeTime rate $+         AbsEventList.fromPairList $ concat l++withMIDIEventsNonblockConstantPause :: (RealField.C time) =>+   ClientName -> time -> time ->+   (EventList.T StrictTime (Maybe Event.T) -> IO a) -> IO a+withMIDIEventsNonblockConstantPause name beat rate proc =+   withInPort name SndSeq.Nonblock $ \ h _p ->+   do l <- ioToLazyList $ threadDelay (round $ flip asTypeOf rate $ beat*1e6) >>+              liftM2 (:)+                 (liftM (\t->(t,Nothing)) getTimeSeconds)+                 (liftM (map (mapSnd Just)) (getWaitingStampedEvents h))+      proc $+         discretizeTime rate $+         AbsEventList.fromPairList $ concat l++withMIDIEventsNonblockSimple :: (RealField.C time) =>+   ClientName -> time -> time ->+   (EventList.T StrictTime Event.T -> IO a) -> IO a+withMIDIEventsNonblockSimple name beat rate proc =+   withInPort name SndSeq.Nonblock $ \ h _p ->+   do l <- ioToLazyList $+              threadDelay (round $ flip asTypeOf rate $ beat*1e6) >>+              getWaitingStampedEvents h+      proc $+         discretizeTime rate $+         AbsEventList.fromPairList $ concat l+++setTimestamping ::+   SndSeq.T mode -> Port.T -> Queue.T -> IO ()+setTimestamping h p q =+   PortInfo.modify h p $ do+      PortInfo.setTimestamping True+      PortInfo.setTimestampReal True+      PortInfo.setTimestampQueue q++withMIDIEventsBlockEcho :: (RealField.C time) =>+   ClientName -> time -> time ->+   (EventList.T StrictTime [Event.T] -> IO a) -> IO a+withMIDIEventsBlockEcho name beat rate proc =+   withInPort name SndSeq.Block $ \ h p ->+   Queue.with h $ \ q ->+   do setTimestamping h p q+      Queue.control h q Event.QueueStart Nothing+      _ <- Event.drainOutput h++      proc .+         discretizeTime rate .+         AbsEventList.fromPairList .+         concat =<<+         (lazySequence $+          flip map (iterate (beat+) 0) $ \t ->+             let end = t+beat+             in  -- (\act -> do evs <- act; print evs; return evs) $+                 -- add a laziness break+                 fmap ((t,[]) :) $+                 fmap (map (mapPair (limit (t,end), (:[])))) $+                 getStampedEventsUntilTime h q p end)++{- |+This is like withMIDIEventsBlockEcho+but collects all events at the beginning of the beats.+This way, further processing steps may collapse+all controller events within one beat to one event.+-}+withMIDIEventsBlockEchoQuantised :: (RealField.C time) =>+   ClientName -> time -> time ->+   (EventList.T StrictTime [Event.T] -> IO a) -> IO a+withMIDIEventsBlockEchoQuantised name beat rate proc =+   withInPort name SndSeq.Block $ \ h p ->+   Queue.with h $ \ q ->+   do Queue.control h q Event.QueueStart Nothing+      _ <- Event.drainOutput h++      proc .+         discretizeTime rate .+         AbsEventList.fromPairList =<<+         (lazySequence $+          flip map (iterate (beat+) 0) $ \t ->+            liftM+               (\evs -> (t, evs))+               (getEventsUntilTime h q p (t+beat)))++{- |+Make sure, that @beat@ is an integer multiple of @recip rate@.+Since we round time within each chunk,+we would otherwise accumulate rounding errors over time.+-}+withMIDIEventsChunked ::+   (RealField.C time) =>+   ClientName -> time -> time ->+   ([IO (EventListTT.T StrictTime [Event.T])] -> IO a) ->+   IO a+withMIDIEventsChunked name beat rate proc =+   withInPort name SndSeq.Block $ \ h p ->+   Queue.with h $ \ q ->+   do setTimestamping h p q+      Queue.control h q Event.QueueStart Nothing+      _ <- Event.drainOutput h++      proc $+         map+            (\t ->+               let end = t+beat+               in  liftM+                      (\evs ->+                         EventListTM.switchBodyR+                            (error "withMIDIEventsChunked: empty list, but there must be at least the end event")+                            const $+                         discretizeTime rate $+                         AbsEventList.fromPairList $+                         (t,[]) :+                         {-+                         FIXME: This is a quick hack in order to assert+                         that all events are within one chunk+                         and do not lie on the boundary.+                         -}+                         map (mapPair (limit (t , end - recip rate), (:[]))) evs +++                         (end, []) :+                         [])+                      (getStampedEventsUntilTime h q p end))+            (iterate (beat+) 0)++withMIDIEventsChunkedQuantised ::+   (RealField.C time) =>+   ClientName -> time -> time ->+   ([IO (EventList.T StrictTime [Event.T])] -> IO a) ->+   IO a+withMIDIEventsChunkedQuantised name beat rate proc =+   withInPort name SndSeq.Block $ \ h p ->+   Queue.with h $ \ q ->+   do Queue.control h q Event.QueueStart Nothing+      _ <- Event.drainOutput h++      proc $+         map+            (\t ->+               liftM+                  (\evs ->+                     EventList.cons NonNeg.zero evs $+                     EventList.singleton+                        (NonNegW.fromNumberMsg "chunked time conversion" $+                         round (beat*rate)) [])+                  (getEventsUntilTime h q p (t+beat)))+            (iterate (beat+) 0)++makeEcho ::+   RealField.C time =>+   Client.T -> Queue.T -> Port.T ->+   time -> Event.Custom -> Event.T+makeEcho c q p t dat =+   (Event.simple+      (Addr.Cons {+           Addr.client = c,+           Addr.port = Port.unknown+        })+      (Event.CustomEv Event.Echo dat))+      { Event.queue = q+      , Event.time =+           Time.consAbs $ Time.Real $ RealTime.fromInteger $+           floor (10^9 * t)+      , Event.dest = Addr.Cons {+           Addr.client = c,+           Addr.port = p+        }+      }++withMIDIEventsBlock :: (RealField.C time) =>+   ClientName -> time ->+   (EventList.T StrictTime Event.T -> IO a) -> IO a+withMIDIEventsBlock name rate proc =+   withInPort name SndSeq.Block $ \ h _p ->+   do l <- ioToLazyList $ getStampedEvent h+      proc $+         discretizeTime rate $+         AbsEventList.fromPairList l++withInPort ::+   ClientName ->+   SndSeq.BlockMode ->+   (SndSeq.T SndSeq.DuplexMode -> Port.T -> IO t) -> IO t+withInPort (ClientName name) blockMode act =+   SndSeq.with SndSeq.defaultName blockMode $ \h ->+   Client.setName h name >>+   Port.withSimple h "input"+      (Port.caps [Port.capWrite, Port.capSubsWrite])+      Port.typeMidiGeneric+      (act h)++{- |+We first discretize the absolute time values,+then we compute differences,+in order to avoid rounding errors in further computations.+-}+discretizeTime :: (RealField.C time) =>+   time -> AbsEventList.T time a -> EventList.T StrictTime a+discretizeTime sampleRate =+   EventListMB.mapTimeHead (const $ NonNegW.fromNumber zero) . -- clear first time since it is an absolute system time stamp+   EventList.fromAbsoluteEventList .+   AbsEventList.mapTime+      (NonNegW.fromNumberMsg "time conversion" . round . (sampleRate*))++++ioToLazyList :: IO a -> IO [a]+ioToLazyList m =+   let go = unsafeInterleaveIO $ liftM2 (:) m go+   in  go++lazySequence :: [IO a] -> IO [a]+lazySequence [] = return []+lazySequence (m:ms) =+   unsafeInterleaveIO $ liftM2 (:) m $ lazySequence ms
+ src/Synthesizer/ALSA/Storable/Play.hs view
@@ -0,0 +1,212 @@+{-# LANGUAGE RebindableSyntax #-}+{- |+Play audio signals via ALSA.+The module could also be called @Output@,+because with a @file@ sink, data can also be written to disk.+-}+module Synthesizer.ALSA.Storable.Play (+   -- * auxiliary functions+   Device,+   defaultDevice,+   defaultChunkSize,+   makeSink,+   write,+   writeLazy,+   -- * play functions+   auto,+   autoAndRecord,+   autoAndRecordMany,+   monoToInt16,+   stereoToInt16,+   ) where++import qualified Sound.ALSA.PCM as ALSA++import qualified Synthesizer.Frame.Stereo as Stereo+import qualified Synthesizer.Basic.Binary as BinSmp++import qualified Sound.Sox.Frame         as SoxFrame+import qualified Sound.Sox.Write         as SoxWrite+import qualified Sound.Sox.Option.Format as SoxOption++import Foreign.Storable (Storable, )+import Foreign.Marshal.Array (advancePtr, )+import Foreign.Ptr (Ptr, minusPtr, )+import Data.Int (Int16, )+import qualified System.IO as IO+import qualified System.Exit as Exit++-- import qualified Synthesizer.State.Signal     as SigS++import qualified Synthesizer.Storable.Signal     as SigSt+import qualified Data.StorableVector.Lazy        as SVL+import qualified Data.StorableVector.Base        as SVB++import qualified Algebra.RealRing as RealRing++import qualified Data.Traversable as Trav+import qualified Data.Foldable as Fold++import NumericPrelude.Numeric+import NumericPrelude.Base+++{- |+A suggested default chunk size.+It is not used by the functions in this module.+-}+{-+Better move to Storable.Server.Common or Dimensional.Server.Common?+-}+defaultChunkSize :: SigSt.ChunkSize+defaultChunkSize = SigSt.chunkSize 512+{-+At some epochs this chunk size leads to buffer underruns.+I cannot reproduce this:+Some months it works this way on Suse but not on Ubuntu or vice versa.+Other months it works the other way round.+defaultChunkSize = SigSt.chunkSize 256+-}+++type Device = String++defaultDevice :: Device+defaultDevice = "default"+++{- |+Useful values for the output device are++* @\"default\"@ for mixing with the output of other applications.++* @\"plughw:0,0\"@ for accessing sound output in an exclusive way.++* @\"tee:default,'output.raw',raw\"@ for playing and simultaneously writing raw data to disk.++* @\"tee:default,'output.wav',wav\"@ for playing and writing to WAVE file format.+  Note that the length cannot be written,+  when the program is terminated,+  leaving the file in an invalid format.+-}+makeSink ::+   (ALSA.SampleFmt y, RealRing.C t) =>+   Device {- ^ ALSA output device -} ->+   t {- ^ period (buffer) size expressed in seconds -} ->+   ALSA.SampleFreq {- ^ sample rate -} ->+   ALSA.SoundSink ALSA.Pcm y+makeSink device periodTime rate =+   ALSA.alsaSoundSinkTime device+      (ALSA.SoundFmt {+         ALSA.sampleFreq = rate+      }) $+   ALSA.SoundBufferTime+      (round (5000000*periodTime))+      (round (1000000*periodTime))++{-+alsaOpen: only few buffer underruns with+       let buffer_time = 200000 -- 0.20s+           period_time =  40000 -- 0.04s++However the delay is still perceivable.++Latency for keyboard playback might be better with:+       let buffer_time =  50000 -- 0.05s+           period_time =  10000 -- 0.01s+but we get too much underruns,+without actually achieving the required latency.+-}+{-# INLINE auto #-}+auto ::+   (ALSA.SampleFmt y) =>+   ALSA.SoundSink handle y ->+   SigSt.T y -> IO ()+auto sink ys =+   ALSA.withSoundSink sink $ \to ->+   writeLazy sink to ys++{-# INLINE writeLazy #-}+writeLazy ::+   (Storable y) =>+   ALSA.SoundSink handle y -> handle y ->+   SVL.Vector y -> IO ()+writeLazy sink to ys =+   mapM_ (write sink to) (SVL.chunks ys)++{-# INLINE write #-}+write ::+   (Storable y) =>+   ALSA.SoundSink handle y -> handle y ->+   SVB.Vector y -> IO ()+write sink to c =+   SVB.withStartPtr c $ \ptr size ->+   ALSA.soundSinkWrite sink to ptr size+++-- cf. Alsa.hs+{-# INLINE arraySize #-}+arraySize :: Storable y => Ptr y -> Int -> Int+arraySize p n = advancePtr p n `minusPtr` p++{- |+Play a signal and write it to disk via SoX simultaneously.+Consider using 'auto' with @tee@ device.+-}+{-# INLINE autoAndRecord #-}+autoAndRecord ::+   (ALSA.SampleFmt y, SoxFrame.C y) =>+   FilePath ->+   ALSA.SoundFmt y ->+   ALSA.SoundSink handle y ->+   SigSt.T y -> IO Exit.ExitCode+autoAndRecord fileName fmt sink =+   let rate = ALSA.sampleFreq fmt+   in  (\act ->+          SoxWrite.simple act SoxOption.none fileName rate) $ \h ys ->+       ALSA.withSoundSink sink $ \to ->+       flip mapM_ (SVL.chunks ys) $ \c ->+       SVB.withStartPtr c $ \ptr size ->+       ALSA.soundSinkWrite sink to ptr size >>+       IO.hPutBuf h ptr (arraySize ptr size)+++{- |+Play a signal and write it to multiple files.+The Functor @f@ may be @Maybe@ for no or one file to write,+or @[]@ for many files to write.+-}+{-# INLINE autoAndRecordMany #-}+autoAndRecordMany ::+   (ALSA.SampleFmt y, SoxFrame.C y,+    Trav.Traversable f) =>+   f FilePath ->+   ALSA.SoundFmt y ->+   ALSA.SoundSink handle y ->+   SigSt.T y -> IO (f Exit.ExitCode)+autoAndRecordMany fileNames fmt sink =+   let rate = ALSA.sampleFreq fmt+   in  (\act ->+          SoxWrite.manyExtended act SoxOption.none SoxOption.none fileNames rate) $ \hs ys ->+       ALSA.withSoundSink sink $ \to ->+       flip mapM_ (SVL.chunks ys) $ \c ->+       SVB.withStartPtr c $ \ptr size ->+       ALSA.soundSinkWrite sink to ptr size >>+       Fold.traverse_ (\h -> IO.hPutBuf h ptr (arraySize ptr size)) hs+++{-# INLINE monoToInt16 #-}+monoToInt16 ::+   (Storable y, RealRing.C y) =>+   ALSA.SoundSink handle Int16 ->+   SigSt.T y -> IO ()+monoToInt16 sink xs =+   auto sink (SigSt.map BinSmp.int16FromCanonical xs)++{-# INLINE stereoToInt16 #-}+stereoToInt16 ::+   (Storable y, RealRing.C y) =>+   ALSA.SoundSink handle (Stereo.T Int16) ->+   SigSt.T (Stereo.T y) -> IO ()+stereoToInt16 sink xs =+   auto sink (SigSt.map (fmap BinSmp.int16FromCanonical) xs)
+ synthesizer-alsa.cabal view
@@ -0,0 +1,126 @@+Cabal-Version:  2.2+Name:           synthesizer-alsa+Version:        0.5.0.6+License:        GPL-3.0-only+License-File:   LICENSE+Author:         Henning Thielemann <haskell@henning-thielemann.de>+Maintainer:     Henning Thielemann <haskell@henning-thielemann.de>+Homepage:       http://www.haskell.org/haskellwiki/Synthesizer+Category:       Sound, Music+Synopsis:       Control synthesizer effects via ALSA/MIDI+Description:+  This package allows to read MIDI events+  and to convert them to control signals+  that can be used for audio effects.+  As demonstration there is a keyboard controlled music synthesizer.+Stability:      Experimental+Tested-With:    GHC==6.4.1, GHC==6.8.2, GHC==6.10.4, GHC==6.12.3+Tested-With:    GHC==7.0.4, GHC==7.2.1+Build-Type:     Simple++Source-Repository this+  Tag:         0.5.0.6+  Type:        darcs+  Location:    http://code.haskell.org/synthesizer/alsa/++Source-Repository head+  Type:        darcs+  Location:    http://code.haskell.org/synthesizer/alsa/++Flag optimizeAdvanced+  description: Enable advanced optimizations. They slow down compilation considerably.+  default:     False++Flag buildExamples+  description: Build example executables+  default:     False++Library+  Build-Depends:+    synthesizer-midi >=0.6 && <0.7,+    synthesizer-dimensional >=0.7 && <0.9,+    synthesizer-core >=0.6 && <0.9,+    midi-alsa >=0.2 && <0.3,+    midi >=0.2 && <0.3,+    sox >=0.2.1 && <0.3,+    alsa-seq >=0.6 && <0.7,+    alsa-pcm >=0.6 && <0.7,+    alsa-core >=0.5 && <0.6,+    storablevector >=0.2.5 && <0.3,+    numeric-prelude >=0.3 && <0.5,+    non-negative >=0.1 && <0.2,+    event-list >=0.1 && <0.2,+    transformers >=0.2 && <0.6,+    utility-ht >=0.0.1 && <0.1,+    random >=1.0 && < 1.3,+    old-time >=1.0 && < 1.2,+    base >=4.5 && <5++  Default-Language: Haskell98+  GHC-Options:    -Wall+  GHC-Options:    -fwarn-unused-do-bind+  Hs-source-dirs: src+  Exposed-modules:+    Synthesizer.ALSA.EventList+    Synthesizer.ALSA.Storable.Play+    Synthesizer.ALSA.Dimensional.Play+    Synthesizer.ALSA.CausalIO.Process++Executable realtimesynth+  If !flag(buildExamples)+    Buildable: False+  If flag(optimizeAdvanced)+    GHC-Options: -fllvm+  GHC-Options: -Wall -fexcess-precision -threaded+-- -ddump-simpl-stats -ddump-asm+  GHC-Options: -fwarn-unused-do-bind+  Default-Language: Haskell98+  Build-Depends:+    synthesizer-alsa,+    synthesizer-midi,+    synthesizer-core,+    midi,+    sox,+    alsa-seq,+    alsa-pcm,+    storablevector,+    numeric-prelude,+    non-negative,+    event-list,+    transformers,+    utility-ht,+    base+  Hs-Source-Dirs: server+  Other-modules:+    Synthesizer.ALSA.Storable.Server.Common+    Synthesizer.ALSA.Storable.Server.Test+    Synthesizer.ALSA.Storable.Server.Run+  Main-Is: Synthesizer/ALSA/Storable/Server.hs++Executable synthicate+  If !flag(buildExamples)+    Buildable: False+  If flag(optimizeAdvanced)+    GHC-Options: -fllvm+  GHC-Options: -Wall -fexcess-precision -threaded+-- -ddump-simpl-stats+  GHC-Options: -fwarn-unused-do-bind+  Default-Language: Haskell98+  Build-Depends:+    synthesizer-alsa,+    synthesizer-midi,+    synthesizer-dimensional,+    synthesizer-core,+    midi,+    alsa-seq,+    alsa-pcm,+    storablevector,+    numeric-prelude,+    event-list,+    base+  Hs-Source-Dirs: server+  Other-modules:+    Synthesizer.ALSA.Dimensional.Server.Common+    Synthesizer.ALSA.Dimensional.Server.Test+    Synthesizer.ALSA.Dimensional.Server.Run+  Main-Is: Synthesizer/ALSA/Dimensional/Server.hs