aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore4
-rw-r--r--COPYING674
-rw-r--r--Makefile39
-rw-r--r--README.md52
-rw-r--r--include/melisma.h130
-rw-r--r--include/melisma/ring.h40
-rw-r--r--melisma.h.pc.sh11
-rw-r--r--melisma.map35
-rw-r--r--src/event.c374
-rw-r--r--src/event.h32
-rw-r--r--src/graph.c466
-rw-r--r--src/graph.h32
-rw-r--r--src/io.c98
-rw-r--r--src/io.h26
-rw-r--r--src/main.c252
-rw-r--r--src/mem.h36
-rw-r--r--src/port.c546
-rw-r--r--src/port.h26
-rw-r--r--src/ring.c158
-rw-r--r--src/util.c33
-rw-r--r--src/util.h26
-rw-r--r--src/version.c62
22 files changed, 3152 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c8af880
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+/melisma
+/melisma.h.pc
+*.o
+*.d
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..14d96e1
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,39 @@
+VERSION := 0.1.0
+PREFIX ?= $(CURDIR)/out
+DESTDIR ?=
+LUA_PC ?= lua-5.3
+CFLAGS := $(shell pkg-config --cflags $(LUA_PC) jack) -MMD -Iinclude -O3
+LDFLAGS := $(shell pkg-config --libs $(LUA_PC) jack) -rdynamic -flto -ldl -Wl,--version-script=melisma.map
+SOURCES := $(wildcard src/*.c)
+OBJECTS := $(SOURCES:%.c=%.o)
+DEPENDS := $(SOURCES:%.c=%.d)
+
+melisma: $(OBJECTS)
+ @ printf "CCLD\t%s\n" $(@)
+ @ $(CC) -o $(@) $(^) $(LDFLAGS)
+
+-include $(DEPENDS)
+
+.c.o:
+ @ printf "CC\t%s\n" $(@)
+ @ $(CC) -o $(@) -c $(<) $(CFLAGS)
+
+install: melisma
+ bash melisma.h.pc.sh $(PREFIX) $(VERSION) $(LUA_PC) >melisma.h.pc
+ install -Dm755 melisma $(DESTDIR)$(PREFIX)/bin/melisma
+ install -Dm644 include/melisma.h $(DESTDIR)$(PREFIX)/include/melisma.h
+ install -Dm644 -t $(DESTDIR)$(PREFIX)/include/melisma include/melisma/*.h
+ install -Dm644 melisma.h.pc $(DESTDIR)$(PREFIX)/share/pkgconfig/melisma.h.pc
+
+clean:
+ rm -rf src/*.o src/*.d melisma.h.pc melisma
+
+debug: CFLAGS += -Wno-cpp -O0 -g
+debug: melisma
+
+sanitize: CFLAGS += -fsanitize=address
+sanitize: LDFLAGS += -fsanitize=address
+sanitize: debug
+
+
+.PHONY: install clean debug
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..fdfce52
--- /dev/null
+++ b/README.md
@@ -0,0 +1,52 @@
+# melisma
+
+Melisma is a scriptable and extensible audio engine. It can be used for
+algorithmic composition, custom digital instruments and interactive audio
+installations. Most of melismas functionality is implemented in Lua modules
+written in C, using an API defined in [melisma.h](../tree/include/melisma.h).
+The core program only implements the Jack client, event system and port
+creation/manipulation. You can find some of my modules [here](../../melisma-modules.git/about),
+and some examples [here](../../melisma-examples.git/about).
+
+## Building and installing
+
+To build melisma from source, you'll need to have pkg-config, Lua 5.3 and Jack
+installed. To build and install, run
+
+```bash
+$ make install PREFIX=/usr/local
+```
+
+## Usage
+
+```bash
+$ melisma script.lua
+```
+
+## Building modules
+
+Melisma modules are written in C. They should be namespaced to melisma, so they
+should be installed to a subdirectory melisma/ in LUA_CPATH, and the entry point
+should look something like this:
+
+```c
+// mymodule.c
+
+#include "melisma.h"
+
+// ...
+
+int luaopen_melisma_mymodule(lua_State *state) {
+ ml_check_version();
+
+ // ...
+
+ return 1;
+}
+```
+
+Building the module may look something like this:
+
+```bash
+$ cc -o mymodule.so -shared -fPIC $(pkg-config --cflags melisma.h) mymodule.c
+```
diff --git a/include/melisma.h b/include/melisma.h
new file mode 100644
index 0000000..11133ec
--- /dev/null
+++ b/include/melisma.h
@@ -0,0 +1,130 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#ifndef MELISMA_H_INCLUDED
+#define MELISMA_H_INCLUDED
+
+#include <lua.h>
+#include <stddef.h>
+#include <sys/poll.h>
+
+#define MELISMA_VERSION "0.1.0"
+#define ml_check_version() ml__check_version(MELISMA_VERSION)
+void ml__check_version(const char *s);
+
+/* Lua metatable tags for builtin types */
+#define MELISMA_NODE_TYPENAME "node"
+#define MELISMA_INPUT_CHANNEL_TYPENAME "input channel"
+#define MELISMA_OUTPUT_CHANNEL_TYPENAME "output channel"
+
+/* Structure passed to each nodes processing function */
+struct ml_proc_args
+{
+ /* Implementation specific data */
+ void *userp;
+
+ /* Number of frames to process */
+ size_t nframes;
+
+ /* Number of input buffers */
+ size_t icnt;
+
+ /* Number of output buffers */
+ size_t ocnt;
+
+ /* List of input buffers */
+ float *const *in;
+
+ /* List of output buffers */
+ float **out;
+};
+typedef struct ml_proc_args ml_proc_args;
+
+/* A node in the audio graph */
+typedef struct ml_node ml_node;
+
+/* An input/output channel of a node */
+typedef struct ml_channel ml_channel;
+
+/* Processing function called for each active node */
+typedef void (*ml_proc_fn)(const ml_proc_args*);
+
+/* Handler for pending IO operations */
+typedef void (*ml_io_handler)(int,int,void*);
+
+/* Create a new node */
+ml_node *ml_create_node(ml_proc_fn proc, void *userp);
+
+/* Add a label to a node */
+#ifdef __GNUC__
+__attribute__((format(printf,2,3)))
+#endif
+void ml_label_node(ml_node *node, const char *fmt, ...);
+
+/* Get a pointer to the root node in the audio graph */
+ml_node *ml_get_root_node(void);
+
+/* Get the user data pointer from a node */
+void *ml_get_userp(ml_node *node);
+
+/* Add an input channel to a node */
+ml_channel *ml_add_input(ml_node *node);
+
+/* Add an output channel to a node */
+ml_channel *ml_add_output(ml_node *node);
+
+/* Get a node input channel by index */
+ml_channel *ml_get_input(ml_node *node, size_t i);
+
+/* Get a node output channel by index */
+ml_channel *ml_get_output(ml_node *node, size_t i);
+
+/* Get the number of input channels for a node */
+size_t ml_num_inputs(ml_node *node);
+
+/* Get the number of output channels for a node */
+size_t ml_num_outputs(ml_node *node);
+
+/* Connect two channels */
+void ml_connect(ml_channel *src, ml_channel *dst);
+
+/* Get the current sample rate */
+unsigned long ml_sample_rate(void);
+
+/* Install a new IO handler for the given file descriptor.
+ * Flags are a combination of POLLIN, POLLOUT etc. */
+void ml_add_io_handler(int fd, int flags, ml_io_handler hdl, void *args);
+
+/* Remove a previously installed IO handler */
+void ml_remove_io_handler(int fd);
+
+typedef long ml_event_id;
+typedef struct
+{
+ ml_event_id id;
+ unsigned long seq;
+} ml_event_handle;
+
+/* Schedule an event from a Lua C function, t samples from the end
+ * of the current processing window. */
+ml_event_handle ml_schedule_event(unsigned long t, int fn, int arg);
+
+/* Cancel a scheduled event from a Lua C function. */
+void ml_cancel_event(const ml_event_handle *hdl);
+
+#endif
diff --git a/include/melisma/ring.h b/include/melisma/ring.h
new file mode 100644
index 0000000..d69e993
--- /dev/null
+++ b/include/melisma/ring.h
@@ -0,0 +1,40 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#ifndef RING_H
+#define RING_H
+
+#include <stdint.h>
+#include <stdatomic.h>
+
+typedef struct ml_ring ml_ring;
+
+ml_ring *ml_ring_init(size_t len);
+void ml_ring_free(ml_ring *r);
+int ml_ring_empty(ml_ring *r);
+int ml_ring_has_space(ml_ring *r, size_t len);
+int ml_ring_put(ml_ring *r, uint8_t c);
+int ml_ring_get(ml_ring *r, uint8_t *c);
+size_t ml_ring_write(ml_ring *r, const void *ptr, size_t len);
+size_t ml_ring_read(ml_ring *r, void *ptr, size_t len);
+void ml_ring_put_blocking(ml_ring *r, uint8_t c);
+uint8_t ml_ring_get_blocking(ml_ring *r);
+void ml_ring_write_blocking(ml_ring *r, const void *ptr, size_t len);
+void ml_ring_read_blocking(ml_ring *r, void *ptr, size_t len);
+
+#endif
diff --git a/melisma.h.pc.sh b/melisma.h.pc.sh
new file mode 100644
index 0000000..c15d177
--- /dev/null
+++ b/melisma.h.pc.sh
@@ -0,0 +1,11 @@
+#! /usr/bin/env bash
+cat <<EOF
+prefix=$1
+includedir=\${prefix}/include
+
+Name: melisma.h
+Description: Melisma module development headers
+Version: $2
+Requires: $3
+Cflags: -I\${includedir}
+EOF
diff --git a/melisma.map b/melisma.map
new file mode 100644
index 0000000..87baac0
--- /dev/null
+++ b/melisma.map
@@ -0,0 +1,35 @@
+MELISMA_0.1.0 {
+ global:
+ ml_create_node;
+ ml_get_root_node;
+ ml_label_node;
+ ml_get_userp;
+ ml_add_input;
+ ml_add_output;
+ ml_get_input;
+ ml_get_output;
+ ml_num_inputs;
+ ml_num_outputs;
+ ml_connect;
+ ml_sample_rate;
+ ml_add_io_handler;
+ ml_remove_io_handler;
+ ml_schedule_event;
+ ml_cancel_event;
+ ml_ring_init;
+ ml_ring_free;
+ ml_ring_empty;
+ ml_ring_has_space;
+ ml_ring_put;
+ ml_ring_get;
+ ml_ring_write;
+ ml_ring_read;
+ ml_ring_put_blocking;
+ ml_ring_get_blocking;
+ ml_ring_write_blocking;
+ ml_ring_read_blocking;
+ ml__check_version;
+
+ local:
+ *;
+};
diff --git a/src/event.c b/src/event.c
new file mode 100644
index 0000000..2d5a41f
--- /dev/null
+++ b/src/event.c
@@ -0,0 +1,374 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#include <stdbool.h>
+
+#include <jack/jack.h>
+
+#include <lua.h>
+#include <lauxlib.h>
+
+#include "mem.h"
+#include "event.h"
+#include "util.h"
+#include "melisma.h"
+
+#define WHEEL_SIZE 4096
+#define MAX_EVENTS 2048
+#define MAINTHREAD_EVENT_CAPACITY (1<<17)
+#define EVENT_HANDLE_TYPENAME "event handle"
+
+struct event
+{
+ ml_event_id id;
+ unsigned long seq;
+ unsigned long rounds;
+ int fn;
+ int arg;
+ ml_event_id next_sched;
+ ml_event_id next_free;
+ bool cancel;
+};
+
+extern jack_client_t *client;
+
+static struct event *pool;
+static size_t pool_len;
+static size_t pool_cap;
+static size_t num_events;
+static size_t counter;
+static ml_event_id free_head = NO_EVENT;
+static ml_event_id wheel[WHEEL_SIZE];
+static size_t cursor;
+static int fn_cache_ref;
+
+static void init_event(ml_event_id id)
+{
+ struct event *e = &pool[id];
+ e->seq = counter++;
+ e->next_free = NO_EVENT;
+ e->next_sched = NO_EVENT;
+ e->cancel = false;
+}
+
+static ml_event_id alloc_event(void)
+{
+ ml_event_id id;
+
+ if (free_head != NO_EVENT)
+ {
+ id = free_head;
+ free_head = pool[id].next_free;
+ goto done;
+ }
+
+ if (pool_len == pool_cap)
+ {
+ pool_cap = pool_cap == 0 ? 64 : pool_cap * 2;
+ pool = srealloc(pool,sizeof(*pool)*pool_cap);
+ }
+
+ id = pool_len++;
+
+done:
+ init_event(id);
+ num_events++;
+ return id;
+}
+
+static void free_event(ml_event_id id)
+{
+ pool[id].seq = (unsigned long) -1;
+
+ if (id == pool_len - 1)
+ {
+ pool_len--;
+ }
+ else
+ {
+ pool[id].next_free = free_head;
+ free_head = id;
+ }
+
+ num_events--;
+}
+
+static void schedule(ml_event_id id, unsigned long t)
+{
+ if (num_events == MAX_EVENTS)
+ {
+ fprintf(stderr,"WARNING: event dropped\n");
+ return;
+ }
+
+ unsigned long rounds = t / WHEEL_SIZE;
+ unsigned long index = (t+cursor) % WHEEL_SIZE;
+ ml_event_id next = wheel[index];
+ ml_event_id prev = NO_EVENT;
+
+ while (next != NO_EVENT && pool[next].rounds <= rounds)
+ {
+ prev = next;
+ next = pool[next].next_sched;
+ }
+
+ if (prev == NO_EVENT)
+ {
+ wheel[index] = id;
+ }
+ else
+ {
+ pool[prev].next_sched = id;
+ }
+
+ pool[id].rounds = rounds;
+ pool[id].next_sched = next;
+}
+
+static bool cancel(long id, long seq)
+{
+ extern lua_State *state;
+ struct event *e = &pool[id];
+
+ if (e->seq == seq)
+ {
+ luaL_unref(state,LUA_REGISTRYINDEX,e->arg);
+ e->arg = LUA_NOREF;
+ e->cancel = true;
+ return true;
+ }
+
+ return false;
+}
+
+ml_event_handle ml_schedule_event(unsigned long t, int fn, int arg)
+{
+ ml_event_id id = alloc_event();
+
+ struct event *e = &pool[id];
+ e->fn = fn;
+ e->arg = arg;
+
+ schedule(id,t);
+
+ ml_event_handle hdl = {
+ .id = id,
+ .seq = e->seq,
+ };
+ return hdl;
+}
+
+void ml_cancel_event(const ml_event_handle *hdl)
+{
+ cancel(hdl->id,hdl->seq);
+}
+
+ml_event_id next_event(unsigned long tmax, unsigned long *t)
+{
+ *t = 0;
+
+ while (true)
+ {
+ if (*t == tmax)
+ {
+ return NO_EVENT;
+ }
+
+ if (cursor == WHEEL_SIZE)
+ {
+ cursor = 0;
+ }
+
+ ml_event_id id = wheel[cursor];
+
+ if (id == NO_EVENT)
+ {
+ cursor++;
+ (*t)++;
+ continue;
+ }
+
+ if (pool[id].rounds > 0)
+ {
+ while (id != NO_EVENT)
+ {
+ pool[id].rounds--;
+ id = pool[id].next_sched;
+ }
+
+ cursor++;
+ (*t)++;
+ continue;
+ }
+
+ wheel[cursor] = pool[id].next_sched;
+
+ if (pool[id].cancel)
+ {
+ free_event(id);
+ continue;
+ }
+
+ return id;
+ }
+}
+
+void dispatch_event(ml_event_id id)
+{
+ struct event *e = &pool[id];
+
+ int fn = e->fn;
+ int arg = e->arg;
+
+ extern lua_State *state;
+
+ lua_rawgeti(state,LUA_REGISTRYINDEX,fn);
+ lua_rawgeti(state,LUA_REGISTRYINDEX,arg);
+
+ if (lua_pcall_with_backtrace(state,1,0) != LUA_OK)
+ {
+ const char *err = luaL_checkstring(state,-1);
+ fprintf(stderr,"%s\n",err);
+ lua_pop(state,1);
+ }
+
+ luaL_unref(state,LUA_REGISTRYINDEX,pool[id].arg);
+
+ free_event(id);
+}
+
+static int make_fn_ref(lua_State *s, int fn)
+{
+ int ref;
+ int top = lua_gettop(s);
+
+ lua_pushvalue(s,fn);
+ fn = lua_gettop(s);
+
+ lua_rawgeti(s,LUA_REGISTRYINDEX,fn_cache_ref);
+ int fn_cache = lua_gettop(s);
+
+ lua_pushvalue(s,fn);
+ lua_gettable(s,fn_cache);
+
+ if (lua_isinteger(s,-1))
+ {
+ ref = lua_tointeger(s,-1);
+ goto done;
+ }
+
+ lua_pushvalue(s,fn);
+ ref = luaL_ref(s,LUA_REGISTRYINDEX);
+
+ lua_pushvalue(s,fn);
+ lua_pushinteger(s,ref);
+ lua_settable(s,fn_cache);
+
+done:
+ lua_settop(s,top);
+ return ref;
+}
+
+static int l_schedule(lua_State *s)
+{
+ float real_t = luaL_checknumber(s,1);
+ luaL_checktype(s,2,LUA_TFUNCTION);
+
+ int fn = make_fn_ref(s,2);
+
+ lua_pushvalue(s,3);
+ int arg = luaL_ref(s,LUA_REGISTRYINDEX);
+
+ unsigned long sr = ml_sample_rate();
+ unsigned long t = sr * real_t;
+
+ ml_event_id id = alloc_event();
+ struct event *e = &pool[id];
+
+ e->fn = fn;
+ e->arg = arg;
+
+ schedule(id,t);
+
+ ml_event_handle *h = lua_newuserdata(s,sizeof *h);
+ luaL_setmetatable(s,EVENT_HANDLE_TYPENAME);
+ h->id = id;
+ h->seq = e->seq;
+
+ return 1;
+}
+
+static int l_cancel(lua_State *s)
+{
+ ml_event_handle *h = luaL_checkudata(s,1,EVENT_HANDLE_TYPENAME);
+ lua_pushboolean(s,cancel(h->id,h->seq));
+ return 1;
+}
+
+static int load_events(lua_State *s)
+{
+ luaL_newmetatable(s,EVENT_HANDLE_TYPENAME);
+
+ lua_newtable(s);
+ int tbl = lua_gettop(s);
+
+ lua_pushcfunction(s,l_schedule);
+ lua_setfield(s,tbl,"schedule");
+
+ lua_pushcfunction(s,l_cancel);
+ lua_setfield(s,tbl,"cancel");
+
+ lua_rawgeti(s,LUA_REGISTRYINDEX,fn_cache_ref);
+ lua_setfield(s,tbl,"function_cache");
+
+ lua_settop(s,tbl);
+ return 1;
+}
+
+static void create_module(lua_State *s)
+{
+ int top = lua_gettop(s);
+
+ lua_getglobal(s,"package");
+ int package = lua_gettop(s);
+
+ lua_getfield(s,package,"preload");
+ int preload = lua_gettop(s);
+
+ lua_pushcfunction(s,load_events);
+ lua_setfield(s,preload,"melisma.event");
+
+ lua_settop(s,top);
+}
+
+static void create_fn_cache(lua_State *s)
+{
+ lua_newtable(s);
+ fn_cache_ref = luaL_ref(s,LUA_REGISTRYINDEX);
+}
+
+void init_events(lua_State *s)
+{
+ create_fn_cache(s);
+ create_module(s);
+
+ for (size_t i = 0; i < WHEEL_SIZE; i++)
+ {
+ wheel[i] = NO_EVENT;
+ }
+}
diff --git a/src/event.h b/src/event.h
new file mode 100644
index 0000000..dd80d80
--- /dev/null
+++ b/src/event.h
@@ -0,0 +1,32 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#ifndef EVENT_H_INCLUDED
+#define EVENT_H_INCLUDED
+
+#include <lua.h>
+
+#include "melisma.h"
+
+#define NO_EVENT ((ml_event_id) -1)
+
+void init_events(lua_State *s);
+ml_event_id next_event(unsigned long tmax, unsigned long *t);
+void dispatch_event(ml_event_id id);
+
+#endif
diff --git a/src/graph.c b/src/graph.c
new file mode 100644
index 0000000..0e1a41e
--- /dev/null
+++ b/src/graph.c
@@ -0,0 +1,466 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdbool.h>
+
+#include <lua.h>
+#include <lauxlib.h>
+
+#include "melisma.h"
+#include "graph.h"
+#include "mem.h"
+
+#ifndef BUFFER_SIZE
+#define BUFFER_SIZE 4096
+#endif
+
+struct ml_channel
+{
+ ml_node *node;
+ enum {IN,OUT} dir;
+ ml_channel *src;
+ ml_channel *next;
+ size_t buf;
+ int refs;
+};
+
+struct ml_node
+{
+ ml_proc_fn proc;
+ void *userp;
+ ml_channel *chans[2];
+ ml_node *next;
+ bool visited;
+ bool cycle;
+ char *label;
+};
+
+struct chunk
+{
+ char *label;
+ ml_proc_fn proc;
+ ml_proc_args args;
+ struct chunk *next;
+ float *data[];
+};
+
+struct free_list
+{
+ size_t buf;
+ struct free_list *next;
+};
+
+static ml_node *root;
+static ml_node *active;
+static ml_node *active_tail;
+static struct free_list *free_list;
+static size_t counter;
+static float *buffers;
+static struct chunk *graph;
+
+ml_node *ml_create_node(ml_proc_fn proc, void *userp)
+{
+ ml_node *node = scalloc(1,sizeof(*node));
+ node->proc = proc;
+ node->userp = userp;
+ return node;
+}
+
+void ml_label_node(ml_node *node, const char *fmt, ...)
+{
+ va_list ap_alloc,ap_print;
+
+ va_start(ap_alloc,fmt);
+ va_copy(ap_print,ap_alloc);
+
+ size_t len = 1 + vsnprintf(NULL,0,fmt,ap_alloc);
+ va_end(ap_alloc);
+
+ char *buf = smalloc(len);
+ vsnprintf(buf,len,fmt,ap_print);
+
+ node->label = buf;
+}
+
+void *ml_get_userp(ml_node *node)
+{
+ return node->userp;
+}
+
+ml_channel *add_channel(ml_node *node, int dir)
+{
+ ml_channel *chan = scalloc(1,sizeof(*chan));
+ chan->dir = dir;
+ chan->node = node;
+
+ if (node->chans[dir] == NULL)
+ {
+ node->chans[dir] = chan;
+ }
+ else
+ {
+ ml_channel *insert = node->chans[dir];
+ while (insert->next)
+ {
+ insert = insert->next;
+ }
+ insert->next = chan;
+ }
+
+ return chan;
+}
+
+ml_channel *ml_add_input(ml_node *node)
+{
+ return add_channel(node,IN);
+}
+
+ml_channel *ml_add_output(ml_node *node)
+{
+ return add_channel(node,OUT);
+}
+
+static ml_channel *get_channel(ml_node *node, size_t i, int dir)
+{
+ ml_channel *chan = node->chans[dir];
+
+ while (i > 0)
+ {
+ if (chan == NULL)
+ {
+ break;
+ }
+
+ i--;
+ chan = chan->next;
+ }
+
+ return chan;
+}
+
+ml_channel *ml_get_input(ml_node *node, size_t i)
+{
+ return get_channel(node,i,IN);
+}
+
+ml_channel *ml_get_output(ml_node *node, size_t i)
+{
+ return get_channel(node,i,OUT);
+}
+
+static size_t num_channels(ml_node *node, int dir)
+{
+ ml_channel *chan = node->chans[dir];
+ size_t n = 0;
+
+ while (chan != NULL)
+ {
+ n++;
+ chan = chan->next;
+ }
+
+ return n;
+}
+
+size_t ml_num_inputs(ml_node *node)
+{
+ return num_channels(node,IN);
+}
+
+size_t ml_num_outputs(ml_node *node)
+{
+ return num_channels(node,OUT);
+}
+
+void ml_connect(ml_channel *src, ml_channel *dst)
+{
+ assert(src->dir == OUT);
+ assert(dst->dir == IN);
+ src->refs++;
+ dst->src = src;
+}
+
+ml_node *ml_get_root_node(void)
+{
+ return root;
+}
+
+void init_graph(lua_State *s)
+{
+ root = ml_create_node(NULL,NULL);
+ ml_label_node(root,"root");
+
+ luaL_newmetatable(s,MELISMA_NODE_TYPENAME);
+ luaL_newmetatable(s,MELISMA_INPUT_CHANNEL_TYPENAME);
+ luaL_newmetatable(s,MELISMA_OUTPUT_CHANNEL_TYPENAME);
+}
+
+static const char *topo_sort(ml_node *node)
+{
+ if (node->visited)
+ {
+ return NULL;
+ }
+
+ if (node->cycle)
+ {
+ return "cycle in audio graph detected";
+ }
+
+ node->visited = true;
+ node->cycle = true;
+
+ ml_channel *in = node->chans[IN];
+
+ while (in != NULL)
+ {
+ if (in->src == NULL)
+ {
+ return "disconnected input channel in audio graph detected";
+ }
+
+ const char *err = topo_sort(in->src->node);
+
+ if (err != NULL)
+ {
+ return err;
+ }
+
+ in = in->next;
+ }
+
+ if (active_tail)
+ {
+ active_tail->next = node;
+ }
+ else
+ {
+ active = node;
+ }
+
+ active_tail = node;
+ node->cycle = false;
+
+ return NULL;
+}
+
+static size_t alloc_buf(void)
+{
+ if (free_list)
+ {
+ struct free_list *head = free_list;
+ size_t buf = head->buf;
+ free_list = head->next;
+ free(head);
+ return buf;
+ }
+
+ return counter++;
+}
+
+static void free_buf(size_t buf)
+{
+ struct free_list *head = scalloc(1,sizeof(*head));
+ head->buf = buf;
+ head->next = free_list;
+ free_list = head;
+}
+
+static void assign_bufs()
+{
+ ml_node *node = active;
+
+ while (node)
+ {
+ ml_channel *in, *out;
+ in = node->chans[IN];
+ out = node->chans[OUT];
+
+ while (out)
+ {
+ out->buf = alloc_buf();
+ out = out->next;
+ }
+
+ while (in)
+ {
+ if (--in->src->refs == 0)
+ {
+ free_buf(in->src->buf);
+ }
+ in = in->next;
+ }
+
+ node = node->next;
+ }
+}
+
+static void make_chunks(void)
+{
+ struct chunk *chunk, *tail = NULL;
+ struct ml_node *node = active;
+
+ while (node)
+ {
+ size_t icnt = ml_num_inputs(node);
+ size_t ocnt = ml_num_outputs(node);
+ size_t nchans = icnt + ocnt;
+ size_t size = sizeof(*chunk) + sizeof(chunk->data[0]) * nchans;
+
+ chunk = scalloc(1,size);
+ chunk->label = node->label ? strdup(node->label) : NULL;
+ chunk->proc = node->proc;
+ chunk->args.userp = node->userp;
+ chunk->args.icnt = icnt;
+ chunk->args.ocnt = ocnt;
+ chunk->args.in = chunk->data;
+ chunk->args.out = chunk->data + icnt;
+
+ ml_channel *in, *out;
+ size_t i = 0;
+
+ in = node->chans[IN];
+
+ while (in != NULL)
+ {
+ chunk->data[i++] = &buffers[BUFFER_SIZE*in->src->buf];
+ in = in->next;
+ }
+
+ out = node->chans[OUT];
+
+ while (out != NULL)
+ {
+ chunk->data[i++] = &buffers[BUFFER_SIZE*out->buf];
+ out = out->next;
+ }
+
+ assert(i == nchans);
+
+ if (tail == NULL)
+ {
+ graph = chunk;
+ }
+ else
+ {
+ tail->next = chunk;
+ }
+
+ tail = chunk;
+ node = node->next;
+ }
+}
+
+const char *build_graph(void)
+{
+ const char *err = topo_sort(root);
+
+ if (err != NULL)
+ {
+ return err;
+ }
+
+ assign_bufs();
+
+ buffers = malloc(sizeof(*buffers)*BUFFER_SIZE*counter);
+
+ make_chunks();
+
+ return NULL;
+}
+
+static void proc_once(size_t n)
+{
+ struct chunk *c = graph;
+ while (c)
+ {
+ if (c->proc)
+ {
+ c->args.nframes = n;
+ c->proc(&c->args);
+ }
+
+ c = c->next;
+ }
+}
+
+void proc_graph(size_t n)
+{
+ while (n > 0)
+ {
+ size_t m = n > BUFFER_SIZE ? BUFFER_SIZE : n;
+ proc_once(m);
+ n -= m;
+ }
+}
+
+static void add_to_layout(lua_State *s, int layout, ml_node *node)
+{
+ int top = lua_absindex(s,lua_gettop(s));
+
+ lua_pushlightuserdata(s,node);
+ lua_gettable(s,layout);
+
+ if (!lua_isnil(s,-1))
+ {
+ return;
+ }
+
+ lua_newtable(s);
+ int tbl = lua_absindex(s,lua_gettop(s));
+
+ if (node->label)
+ {
+ lua_pushstring(s,node->label);
+ lua_setfield(s,tbl,"label");
+ }
+
+ lua_newtable(s);
+ int list = lua_absindex(s,lua_gettop(s));
+ ml_channel *in = node->chans[IN];
+ int i = 1;
+
+ while (in)
+ {
+ add_to_layout(s,layout,in->src->node);
+ lua_pushlightuserdata(s,in->src->node);
+ lua_rawseti(s,list,i++);
+ in = in->next;
+ }
+
+ lua_pushvalue(s,list);
+ lua_setfield(s,tbl,"inputs");
+
+ lua_pushlightuserdata(s,node);
+ lua_pushvalue(s,tbl);
+ lua_settable(s,layout);
+
+ lua_settop(s,top);
+}
+
+int l_graph_layout(lua_State *s)
+{
+ lua_newtable(s);
+ int layout = lua_absindex(s,lua_gettop(s));
+ add_to_layout(s,layout,root);
+ lua_pushvalue(s,layout);
+ return 1;
+}
diff --git a/src/graph.h b/src/graph.h
new file mode 100644
index 0000000..d0f8c28
--- /dev/null
+++ b/src/graph.h
@@ -0,0 +1,32 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#ifndef GRAPH_H_INCLUDED
+#define GRAPH_H_INCLUDED
+
+#include "melisma.h"
+
+#include <lua.h>
+
+void init_graph(lua_State *s);
+const char *build_graph(void);
+void proc_graph(size_t n);
+
+int l_graph_layout(lua_State *s);
+
+#endif
diff --git a/src/io.c b/src/io.c
new file mode 100644
index 0000000..3f60279
--- /dev/null
+++ b/src/io.c
@@ -0,0 +1,98 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#include <stdbool.h>
+
+#include "io.h"
+#include "mem.h"
+
+struct io
+{
+ ml_io_handler hdl;
+ void *args;
+ bool removed;
+};
+
+static struct io *ios;
+static struct pollfd *pollfds;
+static size_t num_fds;
+
+void ml_add_io_handler(int fd, int flags, ml_io_handler hdl, void *args)
+{
+ size_t i = num_fds++;
+ ios = srealloc(ios,sizeof(*ios)*num_fds);
+ pollfds = srealloc(pollfds,sizeof(*pollfds)*num_fds);
+
+ ios[i] = (struct io) {
+ .hdl = hdl,
+ .args = args,
+ };
+
+ pollfds[i] = (struct pollfd) {
+ .fd = fd,
+ .events = flags,
+ };
+}
+
+void ml_remove_io_handler(int fd)
+{
+ for (size_t i = 0; i < num_fds; i++)
+ {
+ if (pollfds[i].fd == fd)
+ {
+ ios[i].removed = true;
+ return;
+ }
+ }
+}
+
+static bool remove_fds(void)
+{
+ for (size_t i = 0; i < num_fds; i++)
+ {
+ if (ios[i].removed)
+ {
+ num_fds--;
+ ios[i] = ios[num_fds];
+ pollfds[i] = pollfds[num_fds];
+ return true;
+ }
+ }
+
+ return false;
+}
+
+void io_loop(void)
+{
+ while (poll(pollfds,num_fds,-1) >= 0)
+ {
+ for (size_t i = 0; i < num_fds; i++)
+ {
+ struct pollfd *p = &pollfds[i];
+ struct io *io = &ios[i];
+
+ if ((p->revents & p->events) && io->hdl)
+ {
+ io->hdl(p->fd,p->revents,io->args);
+ }
+ }
+
+ while (remove_fds())
+ ;
+ }
+}
diff --git a/src/io.h b/src/io.h
new file mode 100644
index 0000000..22fa8df
--- /dev/null
+++ b/src/io.h
@@ -0,0 +1,26 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#ifndef IO_H_INCLUDED
+#define IO_H_INCLUDED
+
+#include "melisma.h"
+
+void io_loop(void);
+
+#endif
diff --git a/src/main.c b/src/main.c
new file mode 100644
index 0000000..b1224a0
--- /dev/null
+++ b/src/main.c
@@ -0,0 +1,252 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <getopt.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include <lua.h>
+#include <lualib.h>
+#include <lauxlib.h>
+
+#include <jack/jack.h>
+
+#include "melisma.h"
+#include "graph.h"
+#include "util.h"
+#include "event.h"
+#include "port.h"
+#include "mem.h"
+#include "io.h"
+
+jack_client_t *client;
+lua_State *state;
+
+static const char *program = NULL;
+static const char *path = NULL;
+static const char *client_name = "melisma";
+static char **script_argv = NULL;
+
+static void usage(FILE *f)
+{
+ fprintf(f,"Usage: %s [OPTION...] [FILE] [ARG...]\n",program);
+ fprintf(f,"Options:\n");
+ fprintf(f,"\t-h Show this help message.\n");
+ fprintf(f,"\t-c NAME Set Jack client name to NAME.\n");
+ fprintf(f,"\t-C PATH Change working directory to PATH.\n");
+}
+
+static void change_cwd(const char *path)
+{
+ if (chdir(path) < 0)
+ {
+ fprintf(stderr,"%s: %s: %s\n",
+ program,path,strerror(errno));
+ exit(EXIT_FAILURE);
+ }
+}
+
+static void parse_args(int argc, char **argv)
+{
+ program = argv[0];
+
+ char c;
+ while ((c = getopt(argc, argv, "hc:C:")) != -1)
+ {
+ switch (c)
+ {
+ case 'h':
+ usage(stdout);
+ exit(EXIT_SUCCESS);
+ case 'c':
+ client_name = optarg;
+ break;
+ case 'C':
+ change_cwd(optarg);
+ break;
+ default:
+ usage(stderr);
+ exit(EXIT_FAILURE);
+ }
+ }
+
+ if (optind < argc && strcmp(argv[optind],"-") != 0)
+ {
+ path = argv[optind];
+ }
+
+ script_argv = &argv[optind + 1];
+}
+
+static int l_sample_rate(lua_State *s)
+{
+ lua_pushinteger(s,ml_sample_rate());
+ return 1;
+}
+
+static int load_internal_module(lua_State *s)
+{
+ lua_newtable(s);
+ int tbl = lua_absindex(s,lua_gettop(s));
+
+ lua_pushcfunction(s,l_graph_layout);
+ lua_setfield(s,tbl,"layout");
+ lua_pushcfunction(s,l_sample_rate);
+ lua_setfield(s,tbl,"samplerate");
+
+ lua_newtable(s);
+ int argv_tbl = lua_gettop(s);
+
+ int i = 1;
+ for (; *script_argv; script_argv++)
+ {
+ lua_pushstring(s,*script_argv);
+ lua_rawseti(s,argv_tbl,i++);
+ }
+
+ lua_settop(s,argv_tbl);
+ lua_setfield(s,tbl,"argv");
+
+ lua_settop(s,tbl);
+ return 1;
+}
+
+static void register_internal_module(lua_State *s)
+{
+ int top = lua_gettop(s);
+
+ lua_getglobal(s,"package");
+ int package = lua_gettop(s);
+
+ lua_getfield(s,package,"preload");
+ int preload = lua_gettop(s);
+
+ lua_pushcfunction(s,load_internal_module);
+ lua_setfield(s,preload,"melisma.internal");
+
+ lua_settop(s,top);
+}
+
+static char *read_stdin(void)
+{
+ size_t len = 0;
+ size_t cap = 0;
+ char *buf = NULL;
+
+ for (;;)
+ {
+ char c = fgetc(stdin);
+
+ if (len == cap)
+ {
+ cap = cap ? 2 * cap : 1024;
+ buf = srealloc(buf, cap);
+ }
+
+ buf[len++] = c == EOF ? 0 : c;
+
+ if (c == EOF)
+ {
+ break;
+ }
+ }
+
+ return buf;
+}
+
+int main(int argc, char **argv)
+{
+ int exitc = EXIT_SUCCESS;
+
+ parse_args(argc,argv);
+
+ client = jack_client_open(client_name,0,NULL);
+
+ if (client == NULL)
+ {
+ fprintf(stderr,"Failed to open Jack client '%s'\n",client_name);
+ exit(EXIT_FAILURE);
+ }
+
+ state = luaL_newstate();
+ luaL_openlibs(state);
+ register_internal_module(state);
+
+ init_graph(state);
+ init_events(state);
+ init_ports(state);
+
+ char *text = NULL;
+ if (path == NULL)
+ {
+ text = read_stdin();
+ if (luaL_loadstring(state,text) != LUA_OK)
+ {
+ const char *err = lua_tostring(state,-1);
+ fprintf(stderr,"%s\n",err);
+ exitc = EXIT_FAILURE;
+ goto cleanup;
+ }
+ }
+ else
+ {
+ if (luaL_loadfile(state,path) != LUA_OK)
+ {
+ const char *err = lua_tostring(state,-1);
+ fprintf(stderr,"%s\n",err);
+ exitc = EXIT_FAILURE;
+ goto cleanup;
+ }
+ }
+
+ if (lua_pcall_with_backtrace(state,0,LUA_MULTRET) != LUA_OK)
+ {
+ const char *err = lua_tostring(state,-1);
+ fprintf(stderr,"%s\n",err);
+ exitc = EXIT_FAILURE;
+ goto cleanup;
+ }
+
+ const char *err = build_graph();
+
+ if (err != NULL)
+ {
+ fprintf(stderr,"Error: %s\n",err);
+ exitc = EXIT_FAILURE;
+ goto cleanup;
+ }
+
+ jack_activate(client);
+
+ ml_add_io_handler(STDIN_FILENO,POLLIN,NULL,NULL);
+ io_loop();
+
+cleanup:
+ free(text);
+ lua_close(state);
+ jack_client_close(client);
+ exit(exitc);
+}
+
+unsigned long ml_sample_rate(void)
+{
+ return jack_get_sample_rate(client);
+}
diff --git a/src/mem.h b/src/mem.h
new file mode 100644
index 0000000..0269213
--- /dev/null
+++ b/src/mem.h
@@ -0,0 +1,36 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#ifndef MEM_H_INCLUDED
+#define MEM_H_INCLUDED
+
+#include <assert.h>
+#include <stdlib.h>
+
+#define safe(func, ...)\
+ ({\
+ void *ptr = func(__VA_ARGS__);\
+ assert(ptr && #func " failed");\
+ ptr;\
+ })
+
+#define smalloc(...) safe(malloc, __VA_ARGS__)
+#define scalloc(...) safe(calloc, __VA_ARGS__)
+#define srealloc(...) safe(realloc, __VA_ARGS__)
+
+#endif
diff --git a/src/port.c b/src/port.c
new file mode 100644
index 0000000..fb487e3
--- /dev/null
+++ b/src/port.c
@@ -0,0 +1,546 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#include <string.h>
+#include <assert.h>
+
+#include <lua.h>
+#include <lauxlib.h>
+
+#include <jack/jack.h>
+#include <jack/midiport.h>
+
+#include "mem.h"
+#include "port.h"
+#include "graph.h"
+#include "event.h"
+
+extern jack_client_t *client;
+
+enum port_type
+{
+ AUDIO_INPUT,
+ MIDI_INPUT,
+ AUDIO_OUTPUT,
+ MIDI_OUTPUT,
+};
+
+struct port
+{
+ enum port_type type;
+ jack_port_t *jack_port;
+ void *jack_buf;
+ int fn;
+ ml_channel *chan;
+ struct port *next;
+};
+
+struct port_descriptor
+{
+ const char *const lua_typename;
+ const char *const jack_typename;
+ const unsigned long jack_flags;
+ const char *const peer_jack_typename;
+ const unsigned long peer_jack_flags;
+ struct port *list;
+};
+
+static struct port_descriptor descriptors[] = {
+ [AUDIO_INPUT] = {
+ .lua_typename = "audio input port",
+ .jack_typename = JACK_DEFAULT_AUDIO_TYPE,
+ .jack_flags = JackPortIsInput,
+ .peer_jack_typename = JACK_DEFAULT_AUDIO_TYPE,
+ .peer_jack_flags = JackPortIsOutput,
+ },
+ [MIDI_INPUT] = {
+ .lua_typename = "midi input port",
+ .jack_typename = JACK_DEFAULT_MIDI_TYPE,
+ .jack_flags = JackPortIsInput,
+ .peer_jack_typename = JACK_DEFAULT_MIDI_TYPE,
+ .peer_jack_flags = JackPortIsOutput,
+ },
+ [AUDIO_OUTPUT] = {
+ .lua_typename = "audio output port",
+ .jack_typename = JACK_DEFAULT_AUDIO_TYPE,
+ .jack_flags = JackPortIsOutput,
+ .peer_jack_typename = JACK_DEFAULT_AUDIO_TYPE,
+ .peer_jack_flags = JackPortIsInput,
+ },
+ [MIDI_OUTPUT] = {
+ .lua_typename = "midi output port",
+ .jack_typename = JACK_DEFAULT_MIDI_TYPE,
+ .jack_flags = JackPortIsOutput,
+ .peer_jack_typename = JACK_DEFAULT_MIDI_TYPE,
+ .peer_jack_flags = JackPortIsInput,
+ },
+};
+
+static void proc(const ml_proc_args *args)
+{
+ struct port *port = args->userp;
+
+ switch (port->type)
+ {
+ case AUDIO_INPUT:
+ memcpy(args->out[0],
+ port->jack_buf,
+ sizeof(*args->out[0])*args->nframes);
+ port->jack_buf = args->nframes + (float*)port->jack_buf;
+ break;
+
+ case AUDIO_OUTPUT:
+ memcpy(port->jack_buf,
+ args->in[0],
+ sizeof(*args->in[0])*args->nframes);
+ port->jack_buf = args->nframes + (float*)port->jack_buf;
+ break;
+
+ case MIDI_INPUT:
+ case MIDI_OUTPUT:
+ assert(0);
+ }
+}
+
+// TODO: Use mutil.h for this when moving to a module
+static ml_channel *get_channel(lua_State *s, int i)
+{
+ ml_channel **c;
+
+ if ((c = luaL_testudata(s,i,MELISMA_OUTPUT_CHANNEL_TYPENAME)) != NULL)
+ {
+ return *c;
+ }
+
+ lua_getfield(s,i,"__ml_out");
+
+ if (!lua_isfunction(s,-1))
+ {
+ lua_pop(s,1);
+ goto error;
+ }
+
+ lua_pushvalue(s,i);
+ lua_call(s,1,1);
+
+ if ((c = luaL_testudata(s,-1,MELISMA_OUTPUT_CHANNEL_TYPENAME)) != NULL)
+ {
+ lua_pop(s,1);
+ return *c;
+ }
+
+ lua_pop(s,1);
+
+error:
+ luaL_argerror(s,i,"expected output channel");
+ return NULL;
+}
+
+static int l_open(lua_State *s)
+{
+ int type_i = lua_upvalueindex(1);
+ enum port_type type = lua_tointeger(s,type_i);
+ struct port_descriptor *pd = &descriptors[type];
+ const char *name = luaL_checkstring(s,1);
+
+ ml_channel *src = NULL;
+
+ if (type == AUDIO_OUTPUT)
+ {
+ src = get_channel(s,2);
+ }
+
+ jack_port_t *jack_port = jack_port_register(client,name,pd->jack_typename,pd->jack_flags,0);
+
+ if (jack_port == NULL)
+ {
+ luaL_error(s,"failed to register port '%s'",name);
+ }
+
+ struct port *port = scalloc(1,sizeof(*port));
+ port->type = type;
+ port->jack_port = jack_port;
+ port->jack_buf = NULL;
+ port->fn = LUA_NOREF;
+ port->next = pd->list;
+ pd->list = port;
+
+ switch (type)
+ {
+ case AUDIO_INPUT:
+ {
+ ml_node *node = ml_create_node(proc,port);
+ port->chan = ml_add_output(node);
+ }
+ break;
+ break;
+
+ case MIDI_INPUT:
+ {
+ }
+ break;
+
+ case AUDIO_OUTPUT:
+ {
+ ml_node *node = ml_create_node(proc,port);
+ ml_channel *out = ml_add_output(node);
+ ml_channel *in = ml_add_input(node);
+ ml_connect(src,in);
+ ml_connect(out,ml_add_input(ml_get_root_node()));
+ }
+ break;
+
+ case MIDI_OUTPUT:
+ {
+ }
+ break;
+ }
+
+ *(void**) lua_newuserdata(s,sizeof(void*)) = port;
+ luaL_setmetatable(s,pd->lua_typename);
+
+ return 1;
+}
+
+static int l_connect(lua_State *s)
+{
+ int type_i = lua_upvalueindex(1);
+ enum port_type type = lua_tointeger(s,type_i);
+ struct port_descriptor *pd = &descriptors[type];
+ struct port *port = *(void**) luaL_checkudata(s,1,pd->lua_typename);
+
+ const char *dst = luaL_checkstring(s,2);
+ const char *src = jack_port_name(port->jack_port);
+
+ if (type == AUDIO_INPUT || type == MIDI_INPUT)
+ {
+ const char *tmp = dst;
+ dst = src;
+ src = tmp;
+ }
+
+ if (jack_connect(client,src,dst) != 0)
+ {
+ luaL_error(s,"failed to connect ports '%s' and '%s'",src,dst);
+ }
+
+ return 0;
+}
+
+static int l_peers(lua_State *s)
+{
+ int type_i = lua_upvalueindex(1);
+ enum port_type type = lua_tointeger(s,type_i);
+ struct port_descriptor *pd = &descriptors[type];
+
+ const char *pattern = luaL_optstring(s,1,"");
+
+ const char *typename = pd->peer_jack_typename;
+ unsigned long flags = pd->peer_jack_flags;
+
+ const char **list = jack_get_ports(client,pattern,typename,flags);
+
+ if (list == NULL)
+ {
+ luaL_error(s,"failed to list ports");
+ }
+
+ lua_newtable(s);
+ int tbl = lua_gettop(s);
+
+ for (int i = 0; list[i] != NULL; i++)
+ {
+ const char *name = list[i];
+
+ jack_port_t *handle = jack_port_by_name(client,name);
+ if (jack_port_is_mine(client,handle))
+ {
+ continue;
+ }
+
+ lua_pushstring(s,list[i]);
+ lua_rawseti(s,tbl,i + 1);
+ }
+
+ jack_free(list);
+
+ lua_settop(s,tbl);
+ return 1;
+}
+
+static int l_callback(lua_State *s)
+{
+ struct port *port = *(void**) luaL_checkudata(s,1,descriptors[MIDI_INPUT].lua_typename);
+ luaL_checktype(s,2,LUA_TFUNCTION);
+ lua_pushvalue(s,2);
+ port->fn = luaL_ref(s,LUA_REGISTRYINDEX);
+ return 1;
+}
+
+static int l_out(lua_State *s)
+{
+ struct port *port = *(void**) luaL_checkudata(s,1,descriptors[AUDIO_INPUT].lua_typename);
+ *(void**) lua_newuserdata(s,sizeof(void*)) = port->chan;
+ luaL_setmetatable(s,MELISMA_OUTPUT_CHANNEL_TYPENAME);
+ return 1;
+}
+
+static int load_ports(lua_State *s)
+{
+ lua_newtable(s);
+ int root = lua_gettop(s);
+
+ {
+ /* AUDIO */
+ lua_newtable(s);
+ int audio = lua_gettop(s);
+
+ lua_pushinteger(s,AUDIO_OUTPUT);
+ lua_pushcclosure(s,l_peers,1);
+ lua_setfield(s,audio,"destinations");
+
+ lua_pushinteger(s,AUDIO_INPUT);
+ lua_pushcclosure(s,l_peers,1);
+ lua_setfield(s,audio,"sources");
+
+ /* AUDIO INPUT */
+ {
+ lua_newtable(s);
+ int audio_input = lua_gettop(s);
+
+ // TODO: Use mutil.h
+ lua_pushcfunction(s,l_out);
+ lua_setfield(s,audio_input,"__ml_out");
+
+ luaL_newmetatable(s,descriptors[AUDIO_INPUT].lua_typename);
+ int audio_input_mt = lua_gettop(s);
+
+ lua_pushvalue(s,audio_input);
+ lua_setfield(s,audio_input_mt,"__index");
+
+ lua_pushinteger(s,AUDIO_INPUT);
+ lua_pushcclosure(s,l_open,1);
+ lua_setfield(s,audio_input,"open");
+
+ lua_pushinteger(s,AUDIO_INPUT);
+ lua_pushcclosure(s,l_connect,1);
+ lua_setfield(s,audio_input,"connect");
+
+ lua_pushvalue(s,audio_input);
+ lua_setfield(s,audio,"input");
+ }
+
+ /* AUDIO OUTPUT */
+ {
+ lua_newtable(s);
+ int audio_output = lua_gettop(s);
+
+ luaL_newmetatable(s,descriptors[AUDIO_OUTPUT].lua_typename);
+ int audio_output_mt = lua_gettop(s);
+
+ lua_pushvalue(s,audio_output);
+ lua_setfield(s,audio_output_mt,"__index");
+
+ lua_pushinteger(s,AUDIO_OUTPUT);
+ lua_pushcclosure(s,l_open,1);
+ lua_setfield(s,audio_output,"open");
+
+ lua_pushinteger(s,AUDIO_OUTPUT);
+ lua_pushcclosure(s,l_connect,1);
+ lua_setfield(s,audio_output,"connect");
+
+ lua_pushvalue(s,audio_output);
+ lua_setfield(s,audio,"output");
+ }
+
+ lua_pushvalue(s,audio);
+ lua_setfield(s,root,"audio");
+ }
+
+ /* MIDI */
+ {
+ lua_newtable(s);
+ int midi = lua_gettop(s);
+
+ lua_pushinteger(s,MIDI_OUTPUT);
+ lua_pushcclosure(s,l_peers,1);
+ lua_setfield(s,midi,"destinations");
+
+ lua_pushinteger(s,MIDI_INPUT);
+ lua_pushcclosure(s,l_peers,1);
+ lua_setfield(s,midi,"sources");
+
+ /* MIDI INPUT */
+ {
+ lua_newtable(s);
+ int midi_input = lua_gettop(s);
+
+ luaL_newmetatable(s,descriptors[MIDI_INPUT].lua_typename);
+ int midi_input_mt = lua_gettop(s);
+
+ lua_pushvalue(s,midi_input);
+ lua_setfield(s,midi_input_mt,"__index");
+
+ lua_pushinteger(s,MIDI_INPUT);
+ lua_pushcclosure(s,l_open,1);
+ lua_setfield(s,midi_input,"open");
+
+ lua_pushinteger(s,MIDI_INPUT);
+ lua_pushcclosure(s,l_connect,1);
+ lua_setfield(s,midi_input,"connect");
+
+ lua_pushinteger(s,MIDI_INPUT);
+ lua_pushcclosure(s,l_callback,1);
+ lua_setfield(s,midi_input,"callback");
+
+ lua_pushvalue(s,midi_input);
+ lua_setfield(s,midi,"input");
+ }
+
+ /* MIDI OUTPUT */
+ {
+ lua_newtable(s);
+ int midi_output = lua_gettop(s);
+
+ luaL_newmetatable(s,descriptors[MIDI_OUTPUT].lua_typename);
+ int midi_output_mt = lua_gettop(s);
+
+ lua_pushvalue(s,midi_output);
+ lua_setfield(s,midi_output_mt,"__index");
+
+ lua_pushinteger(s,MIDI_OUTPUT);
+ lua_pushcclosure(s,l_open,1);
+ lua_setfield(s,midi_output,"open");
+
+ lua_pushinteger(s,MIDI_OUTPUT);
+ lua_pushcclosure(s,l_connect,1);
+ lua_setfield(s,midi_output,"connect");
+
+ lua_pushvalue(s,midi_output);
+ lua_setfield(s,midi,"output");
+ }
+
+ lua_pushvalue(s,midi);
+ lua_setfield(s,root,"midi");
+ }
+
+ lua_settop(s,root);
+ return 1;
+}
+
+static void set_jack_buffers(enum port_type type, size_t n)
+{
+ struct port *port = descriptors[type].list;
+ while (port)
+ {
+ port->jack_buf = jack_port_get_buffer(port->jack_port,n);
+ port = port->next;
+ }
+}
+
+static void schedule_midi_event(unsigned long t, int fn, int status, int data1, int data2)
+{
+ extern lua_State *state;
+ lua_newtable(state);
+ int tbl = lua_absindex(state,lua_gettop(state));
+
+ lua_pushinteger(state,status);
+ lua_setfield(state,tbl,"status");
+
+ lua_pushinteger(state,data1);
+ lua_setfield(state,tbl,"data1");
+
+ lua_pushinteger(state,data2);
+ lua_setfield(state,tbl,"data2");
+
+ int arg = luaL_ref(state,LUA_REGISTRYINDEX);
+ ml_schedule_event(t,fn,arg);
+}
+
+static void flush_midi_events(void)
+{
+ struct port *port = descriptors[MIDI_INPUT].list;
+ for (; port; port = port->next)
+ {
+ if (port->fn == LUA_NOREF)
+ {
+ continue;
+ }
+
+ size_t n = jack_midi_get_event_count(port->jack_buf);
+ for (size_t i = 0; i < n; i++)
+ {
+ jack_midi_event_t e;
+ jack_midi_event_get(&e,port->jack_buf,i);
+ schedule_midi_event(e.time,port->fn,e.buffer[0],e.buffer[1],e.buffer[2]);
+ }
+ }
+}
+
+static int process_callback(jack_nframes_t n, void *args)
+{
+ set_jack_buffers(AUDIO_INPUT,n);
+ set_jack_buffers(MIDI_INPUT,n);
+ set_jack_buffers(AUDIO_OUTPUT,n);
+ set_jack_buffers(MIDI_OUTPUT,n);
+
+ unsigned long t0 = jack_last_frame_time(client);
+ unsigned long t = 0;
+ unsigned long dt = 0;
+ ml_event_id id;
+
+ flush_midi_events();
+
+ while ((id = next_event(n - t, &dt)) != NO_EVENT)
+ {
+ proc_graph(dt);
+ dispatch_event(id);
+
+ t += dt;
+ t0 += dt;
+ }
+
+ proc_graph(dt);
+
+ return 0;
+}
+
+static int xrun_callback(void *args)
+{
+ fprintf(stderr,"XRUN\n");
+ return 0;
+}
+
+void init_ports(lua_State *s)
+{
+ int top = lua_gettop(s);
+
+ lua_getglobal(s,"package");
+ int package = lua_gettop(s);
+
+ lua_getfield(s,package,"preload");
+ int preload = lua_gettop(s);
+
+ lua_pushcfunction(s,load_ports);
+ lua_setfield(s,preload,"melisma.port");
+
+ lua_settop(s,top);
+
+ jack_set_process_callback(client,process_callback,NULL);
+ jack_set_xrun_callback(client,xrun_callback,NULL);
+}
diff --git a/src/port.h b/src/port.h
new file mode 100644
index 0000000..7885d5e
--- /dev/null
+++ b/src/port.h
@@ -0,0 +1,26 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#ifndef PORT_H
+#define PORT_H
+
+#include <lua.h>
+
+void init_ports(lua_State *s);
+
+#endif
diff --git a/src/ring.c b/src/ring.c
new file mode 100644
index 0000000..0bb1553
--- /dev/null
+++ b/src/ring.c
@@ -0,0 +1,158 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#include "mem.h"
+#include "melisma/ring.h"
+
+struct ml_ring
+{
+ _Atomic size_t head;
+ _Atomic size_t tail;
+ size_t len;
+ uint8_t data[];
+};
+
+
+ml_ring *ml_ring_init(size_t len)
+{
+ size_t size = sizeof(ml_ring) + len;
+ ml_ring *r = scalloc(1,size);
+ r->len = len;
+ return r;
+}
+
+void ml_ring_free(ml_ring *r)
+{
+ free(r);
+}
+
+int ml_ring_empty(ml_ring *r)
+{
+ size_t head = atomic_load_explicit(&r->head,memory_order_relaxed);
+ size_t tail = atomic_load_explicit(&r->tail,memory_order_acquire);
+ return tail == head;
+}
+
+int ml_ring_has_space(ml_ring *r, size_t len)
+{
+ size_t head = atomic_load_explicit(&r->head,memory_order_acquire);
+ size_t tail = atomic_load_explicit(&r->tail,memory_order_relaxed);
+ size_t used = tail >= head ? tail - head : r->len - head + tail;
+ size_t free = r->len - 1 - used;
+ return free >= len;
+}
+
+int ml_ring_put(ml_ring *r, uint8_t c)
+{
+ size_t tail = atomic_load_explicit(&r->tail,memory_order_relaxed);
+ size_t head = atomic_load_explicit(&r->head,memory_order_acquire);
+ size_t new_tail = (tail + 1) % r->len;
+
+ if (new_tail == head)
+ {
+ return -1;
+ }
+
+ r->data[tail] = c;
+ atomic_store_explicit(&r->tail,new_tail,memory_order_release);
+
+ return 0;
+}
+
+int ml_ring_get(ml_ring *r, uint8_t *c)
+{
+ size_t tail = atomic_load_explicit(&r->tail,memory_order_acquire);
+ size_t head = atomic_load_explicit(&r->head,memory_order_relaxed);
+ size_t new_head = (head + 1) % r->len;
+
+ if (head == tail)
+ {
+ return -1;
+ }
+
+ *c = r->data[head];
+ atomic_store_explicit(&r->head,new_head,memory_order_release);
+
+ return 0;
+}
+
+size_t ml_ring_write(ml_ring *r, const void *ptr, size_t len)
+{
+ size_t l = 0;
+ const uint8_t *uptr = ptr;
+
+ for (; l < len; l++)
+ {
+ if (ml_ring_put(r,uptr[l]) < 0)
+ {
+ break;
+ }
+ }
+
+ return l;
+}
+
+size_t ml_ring_read(ml_ring *r, void *ptr, size_t len)
+{
+ size_t l = 0;
+ uint8_t *uptr = ptr;
+
+ for (; l < len; l++)
+ {
+ if (ml_ring_get(r,&uptr[l]) < 0)
+ {
+ break;
+ }
+ }
+
+ return l;
+}
+
+void ml_ring_put_blocking(ml_ring *r, uint8_t c)
+{
+ while (ml_ring_put(r,c) < 0)
+ ;
+}
+
+uint8_t ml_ring_get_blocking(ml_ring *r)
+{
+ uint8_t c;
+ while (ml_ring_get(r,&c) < 0)
+ ;
+ return c;
+}
+
+void ml_ring_write_blocking(ml_ring *r, const void *ptr, size_t len)
+{
+ const uint8_t *uptr = ptr;
+
+ while (len--)
+ {
+ ml_ring_put_blocking(r,*(uptr++));
+ }
+}
+
+void ml_ring_read_blocking(ml_ring *r, void *ptr, size_t len)
+{
+ uint8_t *uptr = ptr;
+
+ while (len--)
+ {
+ *(uptr++) = ml_ring_get_blocking(r);
+ }
+}
diff --git a/src/util.c b/src/util.c
new file mode 100644
index 0000000..1b25ae5
--- /dev/null
+++ b/src/util.c
@@ -0,0 +1,33 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <lauxlib.h>
+#include "util.h"
+
+int lua_pcall_with_backtrace(lua_State *s, int n, int r)
+{
+ int f = lua_gettop(s) - n;
+ lua_getglobal(s,"debug");
+ lua_getfield(s,-1,"traceback");
+ lua_remove(s,-2);
+ lua_insert(s,f);
+ int res = lua_pcall(s,n,r,f);
+ lua_remove(s,f);
+ return res;
+}
diff --git a/src/util.h b/src/util.h
new file mode 100644
index 0000000..4851f07
--- /dev/null
+++ b/src/util.h
@@ -0,0 +1,26 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#ifndef UTIL_H_INCLUDED
+#define UTIL_H_INCLUDED
+
+#include <lua.h>
+
+int lua_pcall_with_backtrace(lua_State *s, int n, int r);
+
+#endif
diff --git a/src/version.c b/src/version.c
new file mode 100644
index 0000000..2213bc6
--- /dev/null
+++ b/src/version.c
@@ -0,0 +1,62 @@
+/*
+ * melisma - extensible and scriptable audio engine
+ * Copyright (C) 2026 Ludvig Gunne Lindström
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include "melisma.h"
+#include <lauxlib.h>
+
+struct semver
+{
+ int major;
+ int minor;
+ int patch;
+};
+
+static void parse(struct semver *out, const char *str)
+{
+ const char *tok;
+ char buf[32];
+
+ strcpy(buf, str);
+
+ assert((tok = strtok(buf, ".")));
+ out->major = atoi(tok);
+
+ assert((tok = strtok(NULL, ".")));
+ out->minor = atoi(tok);
+
+ assert((tok = strtok(NULL, ".")));
+ out->patch = atoi(tok);
+}
+
+void ml__check_version(const char *s)
+{
+ extern lua_State *state;
+ struct semver melisma, module;
+
+ parse(&melisma,MELISMA_VERSION);
+ parse(&module,s);
+
+ if (melisma.major != module.major)
+ {
+ luaL_error(state,"Mismatching versions (melisma: %s, module: %s)",
+ MELISMA_VERSION,s);
+ }
+}