diff --git a/.classpath b/.classpath index e4d2178..c022954 100644 --- a/.classpath +++ b/.classpath @@ -6,6 +6,7 @@ + diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml index 01e1e5f..75e1924 100644 --- a/.github/actions/setup/action.yml +++ b/.github/actions/setup/action.yml @@ -3,7 +3,7 @@ name: Set up build environment and dependencies runs: using: "composite" steps: - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v6 with: java-version: '17' distribution: 'temurin' @@ -12,7 +12,7 @@ runs: # cache any custom dependencies (e.g. processing-core.zip) in the library/ # folder so that they don't have to be downloaded every time - - uses: actions/cache@v3 + - uses: actions/cache@v6 with: key: build-deps path: library/ diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 75c05a9..ea1db77 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -8,6 +8,8 @@ jobs: build: runs-on: ubuntu-latest steps: + - name: Check out repository + uses: actions/checkout@v7 - name: Set up build environment and dependencies uses: ./.github/actions/setup - name: Compile diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index ab9a45b..c6052b6 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -7,7 +7,7 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v7 - name: Set up build environment and dependencies uses: ./.github/actions/setup - name: Build library with Ant @@ -15,10 +15,10 @@ jobs: - name: Run tests run: ant test - name: Publish Test Report - uses: mikepenz/action-junit-report@v3 + uses: mikepenz/action-junit-report@v6 with: report_paths: 'TEST-*.xml' - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v7 with: name: sound-jar-${{ github.sha }} path: library/sound.jar @@ -27,7 +27,7 @@ jobs: - name: Generate Javadoc run: ant javadoc - name: Upload GitHub Pages Artifact - uses: actions/upload-pages-artifact@v1 + uses: actions/upload-pages-artifact@v5 with: path: reference/ @@ -50,4 +50,4 @@ jobs: runs-on: ubuntu-latest steps: - name: Deploy to GitHub Pages - uses: actions/deploy-pages@v1 + uses: actions/deploy-pages@v5 diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index d66c994..999d1ac 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -9,7 +9,7 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v7 with: # need this for figuring out the branch name # (see https://stackoverflow.com/questions/63745613/how-to-get-a-branch-name-on-github-action-when-push-on-a-tag) @@ -28,7 +28,7 @@ jobs: run: ant dist dist-android - name: "v* tags only: create version release draft" - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v3 if: startsWith(github.ref, 'refs/tags/v') with: draft: true @@ -39,7 +39,7 @@ jobs: ../sound.txt - name: "`latest` tag only: build latest library download release" - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v3 if: github.ref == 'refs/tags/latest' # just override the assets, otherwise leave the existing release unchanged with: @@ -48,7 +48,7 @@ jobs: ../sound.txt - name: "all other tags: create preliminary test build release" - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v3 if: github.ref != 'refs/tags/latest' && !startsWith(github.ref, 'refs/tags/v') with: name: ${{ github.ref_name }} dev build diff --git a/.gitignore b/.gitignore index 222b34a..c452811 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ .DS_Store TEST-* tags* +.build-deps/ +hs_err_pid*.log diff --git a/build.xml b/build.xml index ef2f473..34fbf0e 100644 --- a/build.xml +++ b/build.xml @@ -7,6 +7,7 @@ + @@ -66,10 +67,29 @@ + + + + + + + + + + + + + + + + + + @@ -113,6 +133,8 @@ + + @@ -140,6 +162,9 @@ + + + diff --git a/examples/IO/AsioOutput/AsioOutput.pde b/examples/IO/AsioOutput/AsioOutput.pde new file mode 100644 index 0000000..08d1c02 --- /dev/null +++ b/examples/IO/AsioOutput/AsioOutput.pde @@ -0,0 +1,168 @@ +/** + * Play a different note on every output channel of an ASIO audio interface, + * bypassing the Windows audio stack for the lowest possible latency. + * + * ASIO support is powered by the JAsioHost bindings and has to be enabled with + * MultiChannel.useJASIO() before any other Sound library call. After the + * switch, all ASIO drivers registered in the system are listed in the console. + * This is a Windows-only feature: on other operating systems (or if no ASIO + * driver is installed) useJASIO() prints an error message and the sketch + * continues with the default audio drivers, so the same sketch runs everywhere. + * + * Tip: if you don't have a driver from your audio interface manufacturer + * installed, try the universal ASIO4ALL driver. + */ + +import processing.sound.*; +import com.synthbot.jasiohost.AsioDriver; +import java.util.List; + +SinOsc[] sines; +int[] notes; +float[] frequencies; +boolean usingASIO; + +// Optional: select a specific ASIO driver by name, exactly as printed by the +// list below. Leave this empty to use the default ASIO output device. +// Example: String asioDriverName = "Focusrite USB ASIO"; +String asioDriverName = ""; + +// Base note (MIDI note number) and scale used to spread different notes over +// the output channels. 48 = C3, 60 = C4. +int baseMidiNote = 48; +final int[] SCALE = {0, 2, 4, 7, 9}; // major pentatonic +final String[] NOTE_NAMES = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}; + +void setup() { + size(640, 360); + background(255); + + // has to be the very first Sound library call of the sketch, before any + // other Sound library objects are created or devices are selected + usingASIO = MultiChannel.useJASIO(); + + if (usingASIO) { + // First list all registered ASIO drivers. We only read the names from the + // registry here: opening every driver one after another can crash some + // manufacturer ASIO drivers. + List asioDrivers = AsioDriver.getDriverNames(); + println("Available ASIO drivers:"); + for (String name : asioDrivers) { + println(" " + name); + } + + // Then select the driver you want to use (see asioDriverName above). + // If that driver is not installed/registered, fall back to the first one. + if (!asioDrivers.isEmpty()) { + try { + if (asioDriverName.length() > 0) { + if (!asioDrivers.contains(asioDriverName)) { + asioDriverName = asioDrivers.get(0); + println("ASIO driver not found, falling back to '" + asioDriverName + "'"); + } + Sound.outputDevice(asioDriverName); + } else { + Sound.defaultOutputDevice(); + } + } catch (RuntimeException e) { + println("Could not open ASIO output device: " + e.getMessage()); + } + } + } + + int channels = MultiChannel.availableChannels(); + if (channels <= 0) { + println("No output channels available."); + return; + } + + println("Playing a different note on each of the " + channels + " output channels" + + (usingASIO ? " of '" + asioDriverName + "'" : " of the default output device")); + + sines = new SinOsc[channels]; + notes = new int[channels]; + frequencies = new float[channels]; + + for (int i = 0; i < channels; i++) { + // route the next oscillator to output channel i + MultiChannel.activeChannel(i); + + sines[i] = new SinOsc(this); + sines[i].amp(0.15f); + sines[i].play(); + } + + // leave multi-channel routing mode so any sounds created later use the + // normal stereo layout again; already-playing sines keep their channels + MultiChannel.activeChannel(-1); + + updateFrequencies(); + printChannelNotes(); + + textSize(12); + textAlign(CENTER, BOTTOM); +} + +void draw() { + if (sines == null || sines.length == 0) { + return; + } + + // transpose all notes together with the mouse + baseMidiNote = 36 + int(map(mouseX, 0, width, 0, 24)); + updateFrequencies(); + + background(255); + drawChannelBars(); + + fill(0); + textSize(16); + textAlign(CENTER, TOP); + text(sines.length + " ASIO output channels", width / 2, 10); +} + +void updateFrequencies() { + for (int i = 0; i < sines.length; i++) { + int octave = i / SCALE.length; + int note = baseMidiNote + SCALE[i % SCALE.length] + 12 * octave; + notes[i] = note; + frequencies[i] = midiToFrequency(note); + sines[i].freq(frequencies[i]); + } +} + +void printChannelNotes() { + for (int i = 0; i < notes.length; i++) { + println(" channel " + i + ": " + noteName(notes[i]) + " (" + nf(frequencies[i], 1, 2) + " Hz)"); + } +} + +void drawChannelBars() { + float margin = 20; + float barWidth = (width - 2 * margin) / sines.length; + float minFrequency = midiToFrequency(24); + float maxFrequency = midiToFrequency(96); + + for (int i = 0; i < sines.length; i++) { + float x = margin + i * barWidth; + float h = map(frequencies[i], minFrequency, maxFrequency, 20, height - 80); + fill(0, 120, 255); + rect(x + 2, height - 40 - h, barWidth - 4, h); + + fill(0); + textSize(10); + textAlign(CENTER, BOTTOM); + text(i, x + barWidth / 2, height - 10); + + textSize(11); + text(noteName(notes[i]), x + barWidth / 2, height - 45); + } +} + +float midiToFrequency(int note) { + return (float) (440.0 * Math.pow(2.0, (note - 69) / 12.0)); +} + +String noteName(int note) { + return NOTE_NAMES[note % 12] + (note / 12 - 1); +} diff --git a/jasiohost-master/.classpath b/jasiohost-master/.classpath new file mode 100644 index 0000000..4d64723 --- /dev/null +++ b/jasiohost-master/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/jasiohost-master/.gitignore b/jasiohost-master/.gitignore new file mode 100644 index 0000000..9f976b0 --- /dev/null +++ b/jasiohost-master/.gitignore @@ -0,0 +1,2 @@ +bin/ +.DS_Store \ No newline at end of file diff --git a/jasiohost-master/.project b/jasiohost-master/.project new file mode 100644 index 0000000..6ae0444 --- /dev/null +++ b/jasiohost-master/.project @@ -0,0 +1,17 @@ + + + JAsioHost + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/jasiohost-master/COPYING b/jasiohost-master/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/jasiohost-master/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/jasiohost-master/COPYING.LESSER b/jasiohost-master/COPYING.LESSER new file mode 100644 index 0000000..fc8a5de --- /dev/null +++ b/jasiohost-master/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/jasiohost-master/JAsioHost.jardesc b/jasiohost-master/JAsioHost.jardesc new file mode 100644 index 0000000..a45737b --- /dev/null +++ b/jasiohost-master/JAsioHost.jardesc @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jasiohost-master/PATCHES.md b/jasiohost-master/PATCHES.md new file mode 100644 index 0000000..c352b43 --- /dev/null +++ b/jasiohost-master/PATCHES.md @@ -0,0 +1,82 @@ +# Local JAsioHost patches + +The prebuilt `jasiohost64.dll` in this directory (and in +`library/windows-amd64/`) is built from the sources in this repository plus the +Steinberg ASIO SDK. The SDK sources are **not** committed because of the +Steinberg license. + +## ASIO SDK version + +The DLL is built against **ASIO SDK 2.3**. The code in SDK 2.3.4 is identical +to 2.3; 2.3.4 only changed the license headers (and introduced a GPLv3 +alternative), so 2.3 is used to keep binary distribution under the classic +Steinberg ASIO license. + +Get the SDK from and extract it somewhere +outside this repository. + +## Patches against the vendored JAsioHost sources + +### `src/com/synthbot/jasiohost/JAsioHost.cpp` + +`ASIOCreateBuffers` used a variable-length array +(`ASIOSampleType sampleTypes[bufferVars.numInitedChannels]`), which is a GCC +extension and does not compile with MSVC. It is replaced with +`std::vector`. No behaviour change. + +## Patches against the ASIO SDK + +### `host/pc/asiolist.cpp` + +The stock Windows enumeration only reads +`HKLM\SOFTWARE\ASIO` in the native registry view. Drivers that are registered +only in the 32-bit view (`HKLM\SOFTWARE\WOW6432Node\ASIO`, written by 32-bit +installers) or per-user (`HKCU\Software\ASIO`) are invisible to a 64-bit host, +even when they ship a 64-bit driver DLL. The rewritten enumerator: + +* scans `HKLM\SOFTWARE\ASIO` in both the 64-bit and 32-bit views (64-bit host) + and `HKCU\Software\ASIO`; +* expands environment variables in `InprocServer32` paths; +* accepts CLSID values with or without braces; +* verifies that the `InprocServer32` DLL exists, is a PE image for the host + architecture and exports `DllGetClassObject` (it is an in-process COM + server) before advertising the driver; +* deduplicates entries by CLSID and by driver name; +* never aborts the scan because of a broken entry. + +The rewritten `asiolist.cpp` is a derivative of the Steinberg SDK, so it is +kept in the local build directory (`.build-deps/build/asiolist_win.cpp`, which +is git-ignored) and not committed. Set `JASIOHOST_DEBUG=1` before launching +the JVM to print the scan report and the rejection reason for each entry to +`stderr`. + +## Rebuilding `jasiohost64.dll` + +Prerequisites: + +* Visual Studio 2019 Build Tools (or newer) with the x64 C++ toolset +* A 64-bit JDK (for `jni.h`) +* ASIO SDK 2.3 extracted somewhere + +Open a `x64 Native Tools Command Prompt` and run, from +`jasiohost-master/src/com/synthbot/jasiohost`: + +```bat +cl /nologo /LD /MT /O2 /EHsc /D_CRT_SECURE_NO_WARNINGS /D_CRT_NONSTDC_NO_DEPRECATE ^ + /I. /I"%ASIOSDK%\common" /I"%ASIOSDK%\host" /I"%ASIOSDK%\host\pc" ^ + /I"%JAVA_HOME%\include" /I"%JAVA_HOME%\include\win32" ^ + JAsioHost.cpp iasiothiscallresolver.cpp ^ + "%ASIOSDK%\common\asio.cpp" "%ASIOSDK%\host\asiodrivers.cpp" ^ + patched-asiolist.cpp ^ + /Fe:jasiohost64.dll /link ole32.lib uuid.lib advapi32.lib user32.lib +``` + +`patched-asiolist.cpp` is the patched copy of `%ASIOSDK%\host\pc\asiolist.cpp` +described above. Do not copy the ASIO SDK into the repository. + +Verify the result with `dumpbin /exports jasiohost64.dll`: the 20 +`Java_com_synthbot_jasiohost_AsioDriver_*` exports must be present and the DLL +must report `8664 machine (x64)`. + +Only `jasiohost64.dll` was rebuilt. `jasiohost32.dll` is still the original +2012 build; Processing 4 runs on a 64-bit JVM, so the 32-bit DLL is not used. diff --git a/jasiohost-master/README.md b/jasiohost-master/README.md new file mode 100644 index 0000000..4401e5b --- /dev/null +++ b/jasiohost-master/README.md @@ -0,0 +1,98 @@ +# About JAsioHost +JAsioHost (JAH) is a Java interface to Steinberg's [Audio Stream Input/Output](http://en.wikipedia.org/wiki/Audio_Stream_Input/Output) (ASIO) API. It provides low-latecy (< 10ms) input and output access to the available audio hardware on **Windows**, replacing the need to use the outdated and slow Java Sound API. + + +## Getting Started +JAsioHost comes in two parts, `JAsioHost.jar` and `jasiohost.dll`. The former is the usual encapsulation of the classes comprising the JAH Java library, and the latter is the JAH interface to ASIO. The package of JAH is `com.synthbot.jasiohost`. + +The library can be quickly tested from the root directory of the project with `java -jar JAsioHost.jar -Djava.library.path=./`. The `ExampleHost` will launch a small GUI allowing you to select an available ASIO driver and use it to play a 440Hz tone. If you're not sure if you have the correct ASIO driver installed (usually soundcard-specific), then try using the excellent [ASIO4ALL](http://www.asio4all.com/) Universal ASIO Driver For WDM Audio. + ++ Include `JAsioHost.jar` in your Java project. ++ Make `jasiohost.dll` available to your project. This can be done in several ways: + + Move or copy the library to `C:\WINDOWS\system32`. This is the default search location for JNI libraries. + + Inform the JVM where the library is located. This can be done with, e.g. `java -Djava.library.path=C:\WINDOWS\system32` + +If the JVM cannot find the dll, an [UnsatisfiedLinkError](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/UnsatisfiedLinkError.html) exception will be thrown. + + +## Example +The basic design pattern for using `JAsioHost` is as follows. `static` methods in `AsioDriver` are used to collect information about the available drivers. `getDriver` is called in order to load and instantiate a given driver. The `AsioDriver` can then be queried for channel state information. Audio buffers are created using `createBuffers`, before `start` is called. Callbacks are made from the driver to registered `AsioDriverListener` objects in order to submit input and retrieve output. + +```Java +// get a list of available ASIO drivers +List driverNameList = AsioDriver.getDriverNames(); + +// load the names ASIO driver +AsioDriver asioDriver = AsioDriver.getDriver(driverNameList.get(0)); + +// add an AsioDriverListener in order to receive callbacks from the driver +asioDriver.addAsioDriverListener(new AsioDriverListener() { + @Override + public void bufferSwitch(long systemTime, long samplePosition, Set channels) { + // fill in audio buffers here + } + + // implement remaining AudioDriverListener interface functions +} + +// create a Set of AsioChannels, defining which input and output channels will be used +Set activeChannels = new HashSet(); + +// configure the ASIO driver to use the given channels +activeChannels.add(asioDriver.getChannelOutput(0)); +activeChannels.add(asioDriver.getChannelOutput(1)); + +// create the audio buffers and prepare the driver to run +asioDriver.createBuffers(); + +// start the driver +asioDriver.start(); +try { + Thread.sleep(1000); +} catch (InterruptedException ie) { + ie.printStackTrace(System.err); +} + +// tear everything down +AsioDriver.shutdownAndUnloadDriver(); +``` + +See the [ExampleHost](https://github.com/mhroth/jasiohost/blob/master/src/com/synthbot/jasiohost/ExampleHost.java) for more details. It also contains a `main` function with a minimum GUI for selecting available drivers. + +Note that you can only load one ASIO driver at time. This is a limitation of the original API (AFAIK). + + +## Note on Compilation +If you are brave enough to try to compile the native component, please note the following helpful tips: + +* I use [Cygwin](http://www.cygwin.com/) to compile the library, and not Visual Studio. Because I am more familiar with the Unix toolchain. This makes some things more difficult. Unfortunate, but so be it. +* You must [download](http://www.steinberg.net/en/company/developer.html) your own copy of the ASIO library. It cannot be distributed here due to licensing restrictions by Steinberg. + +In the ASIO library, +* `./common/asiodrvr.cpp` is not necessary. Rename or remove it. +* `./common/dllentry.cpp` is not necessary. Rename or remove it. +* Line 219 of `./common/combase.h`, `#if WINVER < 0x0501`, should be replaced with `#if 0`. See [here](http://osdir.com/ml/audio.portaudio.devel/2006-09/msg00058.html) for more information. + +The Windows DLL currently shipped with Processing Sound is built with MSVC, +not Cygwin, and uses a patched driver enumerator. See +[PATCHES.md](PATCHES.md) for the exact changes and build command. + + +## A Note about API Translation +The `JAsioHost` API does not strictly reflect the original C++ API written by Steinberg. There are two reasons for this. The first is that some elements of the original API do not translate well due to language semantics. The second is that I felt that some things could be improved or simplified. + +An example of the former is that the native API refers to an audio buffer by using a `void` pointer. Java does not allow arrays to be referenced opaquely. `JAsioHost` therefore encapsulates an audio buffer by using a `ByteBuffer`, which exposes the raw bytes of the native buffer, but also allows other types to be read and written with relative ease. + +An example of the latter is the absence of the `ASIOBufferInfo` structure in Java. I simply added a reference to the audio buffer to the active `AsioChannel` objects. As the audio buffer conceptually belongs to a channel, this seemed to make sense, and also remove a superfluous class. + + +## License +JAsioHost is released under the [Lesser Gnu Public License](http://www.gnu.org/licenses/lgpl.html) (LGPL). Basically, the library stays open source, but you can use if for whatever you want, including closed source applications. You must publicly credit the use of this library. + + +## Acknowledgements +Many thanks to the following people for making JAsioHost possible: +* [Steinberg](http://www.steinberg.net/en/home.html) for releasing ASIO and making good documentation! Of course the ASIO API belongs to them, and if you want to be able to compile the native source then you will need to [get the ASIO component](http://www.steinberg.net/en/company/3rd_party_developer.html) from them. +* This project depends on [IASIOThisCallResolver](http://www.audiomulch.com/~rossb/code/calliasio/). Without it, this project would not be possible. All hail IASIOThisCallResolver. P.S. The reason for this is that I use Cygwin, gcc, MinGW in order to build the native component, not Visual Studio. +* Steve Taylor of [http://toot.org.uk](http://toot.org.uk) for his help in testing out various ASIO drivers and assisting in the debugging process. +* Carl Janson of [HD Sound Lab](hdsoundlab.com) for his efforts in compiling a 64-bit version of the native library. diff --git a/jasiohost-master/jasiohost32.dll b/jasiohost-master/jasiohost32.dll new file mode 100644 index 0000000..1c99a28 Binary files /dev/null and b/jasiohost-master/jasiohost32.dll differ diff --git a/jasiohost-master/jasiohost64.dll b/jasiohost-master/jasiohost64.dll new file mode 100644 index 0000000..39e56bc Binary files /dev/null and b/jasiohost-master/jasiohost64.dll differ diff --git a/jasiohost-master/src/com/synthbot/jasiohost/AsioChannel.java b/jasiohost-master/src/com/synthbot/jasiohost/AsioChannel.java new file mode 100644 index 0000000..027233e --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/AsioChannel.java @@ -0,0 +1,361 @@ +/* + * Copyright 2009 Martin Roth (mhroth@gmail.com) + * + * This file is part of JAsioHost. + * + * JAsioHost is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JAsioHost 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with JAsioHost. If not, see . + * + */ + +package com.synthbot.jasiohost; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * The AsioChannel class represents an input or output channel available form the + * ASIO driver. It provides information such as current state and sample type. This class also + * encapsulates and makes available native audio buffers if it is active. Convenience methods + * are also available to facilitate consuming audio. + */ +public class AsioChannel { + + private final int index; + private final boolean isInput; + private volatile boolean isActive; + private final int channelGroup; + private final AsioSampleType sampleType; + private final String name; + private final ByteBuffer[] nativeBuffers; + private volatile int bufferIndex; + + private static final float MAX_INT16 = (float) 0x00007FFF; + private static final float MAX_INT18 = (float) 0x0001FFFF; + private static final float MAX_INT20 = (float) 0x0007FFFF; + private static final float MAX_INT24 = (float) 0x007FFFFF; + private static final float MAX_INT32 = (float) 0x7FFFFFFF; // Integer.MAX_VALUE + + private AsioChannel(int index, boolean isInput, boolean isActive, int channelGroup, AsioSampleType sampleType, String name) { + this.index = index; + this.isInput = isInput; + this.isActive = isActive; + this.channelGroup = channelGroup; + this.sampleType = sampleType; + this.name = name; + nativeBuffers = new ByteBuffer[2]; + } + + public int getChannelIndex() { + return index; + } + + public boolean isInput() { + return isInput; + } + + public boolean isActive() { + return isActive; + } + + public int getChannelGroup() { + return channelGroup; + } + + public AsioSampleType getSampleType() { + return sampleType; + } + + public String getChannelName() { + return name; + } + + /** + * Returns the current buffer to read or write from, with the position reset to zero. The endian-ness + * of the buffer and of the underlying system has been accounted for. Note that input buffers + * isInput() are read-only. + */ + public ByteBuffer getByteBuffer() { + return nativeBuffers[bufferIndex]; + } + + protected void setBufferIndex(int bufferIndex) { + this.bufferIndex = bufferIndex; + // guard against drivers which fire a straggling bufferSwitch callback while + // or after their buffers have been disposed of (the buffers are cleared to + // null by setByteBuffers() in that case) + if (nativeBuffers[bufferIndex] != null) { + nativeBuffers[bufferIndex].rewind(); // reset position to start of buffer + } + } + + protected void setByteBuffers(ByteBuffer buffer0, ByteBuffer buffer1) { + if (buffer0 == null || buffer1 == null) { + // the ByteBuffer references are cleared + isActive = false; + nativeBuffers[0] = null; + nativeBuffers[1] = null; + } else { + nativeBuffers[0] = isInput ? buffer0.asReadOnlyBuffer() : buffer0; + nativeBuffers[1] = isInput ? buffer1.asReadOnlyBuffer() : buffer1; + if (sampleType.name().contains("MSB")) { + nativeBuffers[0].order(ByteOrder.BIG_ENDIAN); // set the endian-ness of the buffers + nativeBuffers[1].order(ByteOrder.BIG_ENDIAN); // according to the sample type + } else { + nativeBuffers[0].order(ByteOrder.LITTLE_ENDIAN); + nativeBuffers[1].order(ByteOrder.LITTLE_ENDIAN); + } + isActive = true; + } + } + + /** + * A convenience method to write a float array of samples to the output. The array + * values are expected to be bounded to the range of [-1,1]. The need to convert to the correct + * sample type is abstracted. The output array should be same size as the buffer. + * If it is larger, then a BufferOverflowException will be thrown. If it is smaller, + * the buffer will be incompletely filled. + * + * If the ASIO host does not use floats to represent samples, then the AsioChannel's + * ByteBuffer should be directly manipulated. Use getByteBuffer to access the buffer. + * @param output A float array to write to the output. + */ + public void write(float[] output) { + if (isInput) { + throw new IllegalStateException("Only output channels can be written to."); + } + if (!isActive) { + throw new IllegalStateException("This channel is not active: " + toString()); + } + ByteBuffer outputBuffer = getByteBuffer(); + switch (sampleType) { + case ASIOSTFloat64MSB: + case ASIOSTFloat64LSB: { + for (float sampleValue : output) { + outputBuffer.putDouble((double) sampleValue); + } + break; + } + case ASIOSTFloat32MSB: + case ASIOSTFloat32LSB: { + for (float sampleValue : output) { + outputBuffer.putFloat(sampleValue); + } + break; + } + case ASIOSTInt32MSB: + case ASIOSTInt32LSB: { + for (float sampleValue : output) { + outputBuffer.putInt((int) (sampleValue * MAX_INT32)); + } + break; + } + case ASIOSTInt32MSB16: + case ASIOSTInt32LSB16: { + for (float sampleValue : output) { + outputBuffer.putInt((int) (sampleValue * MAX_INT16)); + } + break; + } + case ASIOSTInt32MSB18: + case ASIOSTInt32LSB18: { + for (float sampleValue : output) { + outputBuffer.putInt((int) (sampleValue * MAX_INT18)); + } + break; + } + case ASIOSTInt32MSB20: + case ASIOSTInt32LSB20: { + for (float sampleValue : output) { + outputBuffer.putInt((int) (sampleValue * MAX_INT20)); + } + break; + } + case ASIOSTInt32MSB24: + case ASIOSTInt32LSB24: { + for (float sampleValue : output) { + outputBuffer.putInt((int) (sampleValue * MAX_INT24)); + } + break; + } + case ASIOSTInt16MSB: + case ASIOSTInt16LSB: { + for (float sampleValue : output) { + outputBuffer.putShort((short) (sampleValue * MAX_INT16)); + } + break; + } + case ASIOSTInt24MSB: { + for (float sampleValue : output) { + int sampleValueInt = (int) (sampleValue * MAX_INT24); + outputBuffer.put((byte) ((sampleValueInt >> 16) & 0xFF)); + outputBuffer.put((byte) ((sampleValueInt >> 8) & 0xFF)); + outputBuffer.put((byte) (sampleValueInt & 0xFF)); + } + break; + } + case ASIOSTInt24LSB: { + for (float sampleValue : output) { + int sampleValueInt = (int) (sampleValue * MAX_INT24); + outputBuffer.put((byte) (sampleValueInt & 0xFF)); + outputBuffer.put((byte) ((sampleValueInt >> 8) & 0xFF)); + outputBuffer.put((byte) ((sampleValueInt >> 16) & 0xFF)); + } + break; + } + case ASIOSTDSDInt8MSB1: + case ASIOSTDSDInt8LSB1: + case ASIOSTDSDInt8NER8: { + throw new IllegalStateException( + "The sample types ASIOSTDSDInt8MSB1, ASIOSTDSDInt8LSB1, and ASIOSTDSDInt8NER8 are not supported."); + } + } + } + + /** + * A convenience method to read samples from the input buffer to a float array. + * The argument array must have the same length as the configured buffer size. The returned samples + * are bounded to within [-1,1]. The input array should be the same size as the input + * array. If it larger, then a BufferUnderflowException will be thrown. If it is smaller, + * then the buffer will be incompletely read. + * @param input A float array to read into. + */ + public void read(float[] input) { + if (!isInput) { + throw new IllegalStateException("Only input channels can be read from."); + } + if (!isActive) { + throw new IllegalStateException("This channel is not active: " + toString()); + } + ByteBuffer inputBuffer = getByteBuffer(); + switch (sampleType) { + case ASIOSTFloat64MSB: + case ASIOSTFloat64LSB: { + for (int i = 0; i < input.length; i++) { + input[i] = (float) inputBuffer.getDouble(); + } + break; + } + case ASIOSTFloat32MSB: + case ASIOSTFloat32LSB: { + for (int i = 0; i < input.length; i++) { + input[i] = inputBuffer.getFloat(); + } + break; + } + case ASIOSTInt32MSB: + case ASIOSTInt32LSB: { + for (int i = 0; i < input.length; i++) { + input[i] = ((float) inputBuffer.getInt()) / MAX_INT32; + } + break; + } + case ASIOSTInt32MSB16: + case ASIOSTInt32LSB16: { + for (int i = 0; i < input.length; i++) { + input[i] = ((float) inputBuffer.getInt()) / MAX_INT16; + } + break; + } + case ASIOSTInt32MSB18: + case ASIOSTInt32LSB18: { + for (int i = 0; i < input.length; i++) { + input[i] = ((float) inputBuffer.getInt()) / MAX_INT18; + } + break; + } + case ASIOSTInt32MSB20: + case ASIOSTInt32LSB20: { + for (int i = 0; i < input.length; i++) { + input[i] = ((float) inputBuffer.getInt()) / MAX_INT20; + } + break; + } + case ASIOSTInt32MSB24: + case ASIOSTInt32LSB24: { + for (int i = 0; i < input.length; i++) { + input[i] = ((float) inputBuffer.getInt()) / MAX_INT24; + } + break; + } + case ASIOSTInt16MSB: + case ASIOSTInt16LSB: { + for (int i = 0; i < input.length; i++) { + input[i] = ((float) inputBuffer.getShort()) / MAX_INT16; + } + break; + } + case ASIOSTInt24MSB: { + for (int i = 0; i < input.length; i++) { + int sampleValueInt = ((int) inputBuffer.get()) & 0xFFFF; sampleValueInt <<= 8; + sampleValueInt |= ((int) inputBuffer.get()) & 0xFF; sampleValueInt <<= 8; + sampleValueInt |= ((int) inputBuffer.get()) & 0xFF; + input[i] = ((float) sampleValueInt) / MAX_INT24; + } + break; + } + case ASIOSTInt24LSB: { + for (int i = 0; i < input.length; i++) { + int sampleValueInt = ((int) inputBuffer.get()) & 0xFF; + sampleValueInt |= (((int) inputBuffer.get()) & 0xFF) << 8; + sampleValueInt |= (((int) inputBuffer.get()) & 0xFFFF) << 16; + input[i] = ((float) sampleValueInt) / MAX_INT24; + } + break; + } + case ASIOSTDSDInt8MSB1: + case ASIOSTDSDInt8LSB1: + case ASIOSTDSDInt8NER8: { + throw new IllegalStateException( + "The sample types ASIOSTDSDInt8MSB1, ASIOSTDSDInt8LSB1, and ASIOSTDSDInt8NER8 are not supported."); + } + } + } + + /* + * equals() is overridden such that it may be used in a Set + */ + @Override + public boolean equals(Object o) { + if (!(o instanceof AsioChannel)) { + return false; + } else { + AsioChannel channelInfo = (AsioChannel) o; + return (channelInfo.getChannelIndex() == index && channelInfo.isInput() == isInput); + } + } + + /* + * hashCode() overridden in order to accompany equals() + */ + @Override + public int hashCode() { + return isInput ? index : ~index + 1; // : 2's complement + } + + /** + * Returns a string description of the channel in the format, + * "Output Channel 0: Analog Out 1/2 Delta-AP [1], ASIOSTInt32LSB, group 0, inactive" + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(isInput ? "Input" : "Output"); + sb.append(" Channel "); sb.append(Integer.toString(index)); + sb.append(": "); sb.append(name); + sb.append(", "); sb.append(sampleType.toString()); + sb.append(", group "); sb.append(Integer.toString(channelGroup)); + sb.append(", "); sb.append(isActive ? "active" : "inactive"); + return sb.toString(); + } +} diff --git a/jasiohost-master/src/com/synthbot/jasiohost/AsioDriver.java b/jasiohost-master/src/com/synthbot/jasiohost/AsioDriver.java new file mode 100644 index 0000000..309378a --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/AsioDriver.java @@ -0,0 +1,668 @@ +/* + * Copyright 2009,2010,2012 Martin Roth (mhroth@gmail.com) + * + * This file is part of JAsioHost. + * + * JAsioHost is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JAsioHost 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with JAsioHost. If not, see . + * + */ + +package com.synthbot.jasiohost; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * The AsioDriver class represents an ASIO driver. Only one may be loaded at any + * time. A new driver is instantiated with getDriver(), supplied with the name of the + * driver to load, as derived from getDriverNames().
+ *
+ * All methods may throw an AsioException, which is a RuntimeException + * (i.e., it is not required to be caught). The error message will have some information about + * what has gone wrong. Generally, it is not possible to recover from such errors, except for + * shutting down the driver.
+ *
+ * Note that most methods also throw an IllegalStateException if the driver is not + * in the appropriate state for that method to be called. For instance, if start() + * is called before createBuffers(), an IllegalStateException will be + * thrown.
+ *
+ * After the driver has been instantiated with getDriver(), the sequence of setup calls + * are: createBuffers() and then start(). Once the driver has been started, + * bufferSwitch() will be called on any AsioDriverListeners and audio can be + * sent or received from the driver. In order to shut down the driver from the RUNNING + * state, call: stop(), disposeBuffers(), exit(), and + * finally unloadDriver() (if the driver should be fully unloaded from memory). Alternatively + * returnToState() can also be used in order to return the AsioDriver to + * a particular AsioDriverState. + */ +public class AsioDriver { + + private AsioDriverState currentState; + private final List listeners; + private final Set activeChannels; + private final AsioChannel[] inputChannels; + private final AsioChannel[] outputChannels; + private final AsioDriverInfo driverInfo; + + private static AsioDriver asioDriver; // The currently loaded ASIO driver. + private static final Set registeredThreads; // threads registered to access the native driver + + private AsioDriver(String driverName) { + registerThreadIfNecessary(); + + boolean driverLoaded = loadDriver(driverName); // load the driver into memory + if (!driverLoaded) { + throw new AsioException("The driver was not successfully loaded into memory. " + + "The Steinberg ASIO API does not indicate why."); + } + driverInfo = ASIOInit(); // initialise the driver + currentState = AsioDriverState.INITIALIZED; + activeChannels = new HashSet(); + asioDriver = this; + + listeners = new ArrayList(); + + inputChannels = new AsioChannel[ASIOGetChannels(true)]; + for (int i = 0; i < inputChannels.length; i++) { + inputChannels[i] = ASIOGetChannelInfo(i, true); + } + outputChannels = new AsioChannel[ASIOGetChannels(false)]; + for (int i = 0; i < outputChannels.length; i++) { + outputChannels[i] = ASIOGetChannelInfo(i, false); + } + } + + /** + * The designated ASIO driver is loaded and returned in the INITIALIZED state. If a driver is + * already loaded and it is the named driver, then that driver object is returned. If the named + * driver is different from the one currently loaded, then the currently loaded driver is shut + * down and a new one is instantiated. There is only ever one loaded driver. + * + * @param driverName The name of the driver to load, as returned by getDriverNames(). + * @return The named AsioDriver object. + * @throws AsioException Thrown if the driver could not be loaded into memory. + * @throws NullPointerException Thrown if the input is null. + */ + public static AsioDriver getDriver(String driverName) { + if (driverName == null) { + throw new NullPointerException("The driver name cannot be null."); + } + if (isDriverLoaded()) { + if (driverName.equals(asioDriver.getName())) { + return asioDriver; + } else { + asioDriver.shutdownAndUnloadDriver(); + } + } + if (getDriverNames().contains(driverName)) { + asioDriver = new AsioDriver(driverName); + return asioDriver; + } else { + throw new IllegalArgumentException( + "The given driver name does not exist in the system registry. " + + "Check AsioDriver.getDriverNames()."); + } + } + + private static void registerThreadIfNecessary() { + if (registeredThreads.isEmpty()) { + // the first thread to access native code does not have to be registered + // ...it does so implicitly by accessing the ASIO code for the first time + registeredThreads.add(Thread.currentThread()); + } else if (!registeredThreads.contains(Thread.currentThread())) { + registeredThreads.add(Thread.currentThread()); + registerThread(); + } + } + + /** + * Due to the way in which ASIO drivers are integrated into Windows (as COM objects), + * it is necessary to register each thread which accesses any ASIO methods. Such + * registration is done automatically for the thread which loads the AsioDriver + * class (usually the first thread to access any AsioDriver method). Failure to register + * additional threads may cause exceptions, non-function of methods, or other arbitrary behaviour. + * A thread may register itself more than once, but this is not necessary. Registration is lightweight. + */ + private static native void registerThread(); + + /** + * Returns the currently loaded AsioDriver. If no driver is loaded, null + * is returned. Check to see if a driver is currently loaded with isDriverLoaded(). + */ + public static AsioDriver getCurrentDriver() { + return asioDriver; + } + + static { + // load jasiohost32.dll or jasiohost64.dll depending on the the bit-depth of the JVM + System.loadLibrary("jasiohost" + System.getProperty("sun.arch.data.model")); + registeredThreads = new HashSet(); + } + + /** + * Returns true if a driver is currently loaded, false otherwise. + */ + public static boolean isDriverLoaded() { + return asioDriver != null; + } + + /** + * A list of all (maximum 32) ASIO drivers registered with the system is returned. + */ + public static List getDriverNames() { + registerThreadIfNecessary(); + String[] driverNames = new String[32]; + int numNames = getDriverNames(driverNames); + List nameList = new ArrayList(numNames); + for (int i = 0; i < numNames; i++) { + nameList.add(driverNames[i]); + } + return nameList; + } + private static native int getDriverNames(String[] driverNames); + + /* + * Normally the driver is shut down manually. But it is put into finalize() in order to properly + * shut down the driver in case the JVM is otherwise stopped. + * (non-Javadoc) + * @see java.lang.Object#finalize() + */ + @Override + protected void finalize() throws Throwable { + try { + returnToState(AsioDriverState.UNLOADED); + } finally { + super.finalize(); + } + } + + /** + * Returns the name of the driver. + */ + public String getName() { + return driverInfo.getDriverName(); + } + + /** + * Returns the version of the driver. + */ + public int getVersion() { + return driverInfo.getDriverVersion(); + } + + /** + * Returns the version of ASIO which this driver uses (currently 1 or 2). + */ + public int getAsioVersion() { + return driverInfo.getAsioVersion(); + } + + /** + * Returns the current state of the ASIO driver. + */ + public synchronized AsioDriverState getCurrentState() { + return currentState; + } + + private native AsioDriverInfo ASIOInit(); + + /** + * Closes all data structures relating to the operation of the ASIO driver, though the driver + * remains loaded in memory. Returns the driver from the INITIALIZED state to the + * LOADED state. + */ + public synchronized void exit() { + if (!AsioDriverState.INITIALIZED.equals(currentState)) { + throw new IllegalStateException("AsioDriver must be in AsioDriverState.INITIALIZED state " + + "in order to be initialised. The current state is: " + currentState.toString()); + } + registerThreadIfNecessary(); + ASIOExit(); + currentState = AsioDriverState.LOADED; + } + private native void ASIOExit(); + + /** + * Open the native control panel, allowing the user to adjust the ASIO settings. A control panel + * may not be provided by all drivers on all platforms. + */ + public synchronized void openControlPanel() { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + registerThreadIfNecessary(); + ASIOControlPanel(); + } + private static native void ASIOControlPanel(); + + /** + * Returns the number of available input channels. -1 is returned if there is an error. + * @return The number of available input channels. + */ + public int getNumChannelsInput() { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + return inputChannels.length; + } + + /** + * Returns the number of available output channels. -1 is return if there is an error. + * @return The number of available output channels. + */ + public int getNumChannelsOutput() { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + return outputChannels.length; + } + private static native int ASIOGetChannels(boolean isInput); + + /** + * Returns the current sample rate to which the host is set. + * @return The current sample rate in Hz. + */ + public synchronized double getSampleRate() { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + registerThreadIfNecessary(); + return ASIOGetSampleRate(); + } + private static native double ASIOGetSampleRate(); + + /** + * Inquires of the hardware if a specific available sample rate is available. + * @param sampleRate The sample rate in Hz. + * @return True if the sample rate is supported. False otherwise. + */ + public synchronized boolean canSampleRate(double sampleRate) { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + registerThreadIfNecessary(); + return ASIOCanSampleRate(sampleRate); + } + private static native boolean ASIOCanSampleRate(double sampleRate); + + /** + * Set the hardware to the requested sample Rate. If sampleRate == 0, enable external sync. + * The driver must be in the INITIALIZED state. + * @param sampleRate The sample rate in Hz. + */ + public synchronized void setSampleRate(double sampleRate) { + if (currentState.ordinal() != AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be in the INITIALIZED state: " + + currentState.toString()); + } + registerThreadIfNecessary(); + ASIOSetSampleRate(sampleRate); + } + private static native void ASIOSetSampleRate(double sampleRate); + + /** + * Returns the minimum supported buffer size. + */ + public synchronized int getBufferMinSize() { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + registerThreadIfNecessary(); + return ASIOGetBufferSize(0); + } + + /** + * Returns the maximum supported buffer size. + */ + public synchronized int getBufferMaxSize() { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + currentState.toString()); + } + registerThreadIfNecessary(); + return ASIOGetBufferSize(1); + } + + /** + * Returns the preferred buffer size. The host should attempt to use this buffer size. + */ + public synchronized int getBufferPreferredSize() { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + currentState.toString()); + } + registerThreadIfNecessary(); + return ASIOGetBufferSize(2); + } + + /** + * Returns the granularity at which buffer sizes may differ. Usually, the buffer size will be + * a power of 2; in this case, granularity will be reported as -1, signaling possible + * buffer sizes starting from the minimum size, increased in powers of 2 up to maximum size. + */ + public synchronized int getBufferGranularity() { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + registerThreadIfNecessary(); + return ASIOGetBufferSize(3); + } + + private static native int ASIOGetBufferSize(int index); + + /** + * Note: As getLatencyInput() will also have to include the audio buffer size of the + * createBuffers() call, the application should call this function after the buffer creation. + * In the case that the call occurs beforehand the driver should assume preferred buffer size. + * @return The input latency in samples. + */ + public synchronized int getLatencyInput() { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + registerThreadIfNecessary(); + return ASIOGetLatencies(true); + } + + /** + * Note: As getLatencyOutput() will also have to include the audio buffer size of the + * createBuffers() call, the application should call this function after the buffer creation. + * In the case that the call occurs beforehand the driver should assume preferred buffer size. + * @return The output latency in samples. + */ + public synchronized int getLatencyOutput() { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + registerThreadIfNecessary(); + return ASIOGetLatencies(false); + } + private static native int ASIOGetLatencies(boolean isInput); + + /** + * Get information about an input channel. The returned AsioChannel object + * is persistent for as long as the driver is INITIALIZED, and can be retrieved + * in any context. + * @param index The input channel index to get information about. + * @return An AsioChannel object representing the requested input channel. + * @throws IndexOutOfBoundsException Thrown if the requested channel index is out of bounds. The + * channel does not exist. + */ + public synchronized AsioChannel getChannelInput(int index) { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + if (index < 0 || index >= inputChannels.length) { + throw new IndexOutOfBoundsException("The input index must be in [0," + + Integer.toString(inputChannels.length) + "): " + Integer.toString(index)); + } + return inputChannels[index]; + } + + /** + * Get information about an output channel. The returned AsioChannel object + * is persistent for as long as the driver is INITIALIZED, and can be retrieved + * in any context. + * @param index The output channel index to get information about. + * @return An AsioChannel object representing the requested output channel. + * @throws IndexOutOfBoundsException Thrown if the requested channel index is out of bounds. The + * channel does not exist. + */ + public synchronized AsioChannel getChannelOutput(int index) { + if (currentState.ordinal() < AsioDriverState.INITIALIZED.ordinal()) { + throw new IllegalStateException("The AsioDriver must be at least in the INITIALIZED state: " + + currentState.toString()); + } + if (index < 0 || index >= outputChannels.length) { + throw new IndexOutOfBoundsException("The output index must be in [0," + + Integer.toString(outputChannels.length) + "): " + Integer.toString(index)); + } + return outputChannels[index]; + } + private static native AsioChannel ASIOGetChannelInfo(int index, boolean isInput); + + /** + * Creates audio buffers for the set of designated channels. The buffer size is that as returned by + * getBufferPreferredSize(). + * @param channelsToInit A Set of AsioChannelInfo objects designating the + * input and output channels to initialise and create audio buffers for. + */ + public synchronized void createBuffers(Set channelsToInit) { + if (!AsioDriverState.INITIALIZED.equals(currentState)) { + throw new IllegalStateException("The ASIO driver must be in the INITIALIZED state in order to createBuffers()."); + } + if (channelsToInit == null) { + throw new NullPointerException("The set of channels to initialise may not be null."); + } + if (channelsToInit.contains(null)) { + throw new IllegalArgumentException("The set of channels to initialise may not contain a null value."); + } + if (channelsToInit.size() == 0) { + throw new IllegalArgumentException("The set of channels to initialise may not be empty."); + } + + // make a defensive copy of the the channel initialisation set + activeChannels.addAll(channelsToInit); + + registerThreadIfNecessary(); + ASIOCreateBuffers(activeChannels.toArray(new AsioChannel[0]), getBufferPreferredSize()); + + currentState = AsioDriverState.PREPARED; + } + private static native void ASIOCreateBuffers(AsioChannel[] channelsToInit, int bufferSize); + + /** + * Remove the previously created audio buffers (with createBuffers()). The active + * channels are reset; all channels become inactive. + */ + public synchronized void disposeBuffers() { + if (!AsioDriverState.PREPARED.equals(currentState)) { + throw new IllegalStateException("The ASIO driver must be in the PREPARED state " + + "in order to dispose of the audio buffers."); + } + for (AsioChannel channelInfo : activeChannels) { + channelInfo.setByteBuffers(null, null); // clear the ByteBuffer references + } + activeChannels.clear(); + registerThreadIfNecessary(); + ASIODisposeBuffers(); + currentState = AsioDriverState.INITIALIZED; + } + private static native void ASIODisposeBuffers(); + + /** + * Start the driver. Input buffers are presented and output buffers consumed via calls to + * bufferSwitch(). Puts the AsioDriver into the RUNNING state. + */ + public synchronized void start() { + if (!AsioDriverState.PREPARED.equals(currentState)) { + throw new IllegalStateException(); + } + registerThreadIfNecessary(); + ASIOStart(); + currentState = AsioDriverState.RUNNING; + } + private static native void ASIOStart(); + + /** + * Stop the driver. Calls to bufferSwitch() will cease. The AsioDriver + * returns to the PREPARED state. + */ + public synchronized void stop() { + if (!AsioDriverState.RUNNING.equals(currentState)) { + throw new IllegalStateException(); + } + registerThreadIfNecessary(); + ASIOStop(); + currentState = AsioDriverState.PREPARED; + } + private static native void ASIOStop(); + + /** + * Loads the named driver into memory. + * @param driverName The ASIO driver to load. + * @return True if the driver was successfully loaded. False otherwise. + */ + private static native boolean loadDriver(String driverName); + + private synchronized void unloadDriver() { + if (!AsioDriverState.LOADED.equals(currentState)) { + throw new IllegalStateException(); + } + registerThreadIfNecessary(); + removeCurrentDriver(); + currentState = AsioDriverState.UNLOADED; + asioDriver = null; + } + private static native void removeCurrentDriver(); + + /** + * Shutdown the ASIO driver, regardless of what state it is in. Unload it from memory. This is a + * convenience method for returnToState(AsioDriverState.UNLOADED). + */ + public synchronized void shutdownAndUnloadDriver() { + returnToState(AsioDriverState.UNLOADED); + } + + /** + * Return the driver to a given state. If the target state is ahead or equal to the current state + * then this method has no effect. + * @param targetState The state to which the driver should return. + */ + public synchronized void returnToState(AsioDriverState targetState) { + if (targetState == null) { + throw new NullPointerException("Target state may not be null."); + } + if (targetState.ordinal() < currentState.ordinal()) { + switch (currentState) { + case RUNNING: { + stop(); + if (currentState.equals(targetState)) { + break; + } + // allow fall-throughs + } + case PREPARED: { + disposeBuffers(); + if (currentState.equals(targetState)) { + break; + } + } + case INITIALIZED: { + exit(); + if (currentState.equals(targetState)) { + break; + } + } + case LOADED: { + unloadDriver(); + break; + } + default: { + // do nothing + } + } + } + } + + /** + * Add a new AsioDriverListener. Listeners can only be updated while the driver + * is in the LOADED or INITIALIZED state. + * @param listener A new AsioDriverListener which should be sent callbacks. + */ + public synchronized void addAsioDriverListener(AsioDriverListener listener) { + if (currentState.ordinal() < AsioDriverState.PREPARED.ordinal()) { + if (!listeners.contains(listener)) { + listeners.add(listener); + } + } else { + throw new IllegalStateException("AsioDriverListeners can only be updated while the " + + "AsioDriver is in the LOADED or INITIALIZED state."); + } + } + + /** + * Unregister an AsioDriverListener. Listeners can only be updated while the driver + * is in the LOADED or INITIALIZED state. + * @param listener A previously registered AsioDriverListener. + */ + public synchronized void removeAsioDriverListener(AsioDriverListener listener) { + if (currentState.ordinal() < AsioDriverState.PREPARED.ordinal()) { + listeners.remove(listener); + } else { + throw new IllegalStateException("AsioDriverListeners can only be updated while the " + + "AsioDriver is in the LOADED or INITIALIZED state."); + } + } + + + /* + * Callbacks + */ + + private void fireSampleRateDidChange(double sampleRate) { + for (AsioDriverListener listener : listeners) { + listener.sampleRateDidChange(sampleRate); + } + } + + private void fireResetRequest() { + for (AsioDriverListener listener : listeners) { + listener.resetRequest(); + } + } + + private void fireResyncRequest() { + for (AsioDriverListener listener : listeners) { + listener.resyncRequest(); + } + } + + private void fireBufferSizeChanged(int bufferSize) { + for (AsioDriverListener listener : listeners) { + listener.bufferSizeChanged(bufferSize); + } + } + + private void fireLatenciesChanged(int inputLatency, int outputLatency) { + for (AsioDriverListener listener : listeners) { + listener.latenciesChanged(inputLatency, outputLatency); + } + } + + private void fireBufferSwitch(long systemTime, long samplePosition, int bufferIndex) { + for (AsioChannel channel : inputChannels) { + if (channel.isActive()) channel.setBufferIndex(bufferIndex); + } + for (AsioChannel channel : outputChannels) { + if (channel.isActive()) channel.setBufferIndex(bufferIndex); + } + // NOTE(mhroth): use a standard for loop in order to avoid implicitly creating iterator objects + // as this function is called very often + for (int i = 0; i < listeners.size(); i++) { + listeners.get(i).bufferSwitch(systemTime, samplePosition, activeChannels); + } + } +} diff --git a/jasiohost-master/src/com/synthbot/jasiohost/AsioDriverInfo.java b/jasiohost-master/src/com/synthbot/jasiohost/AsioDriverInfo.java new file mode 100644 index 0000000..09b45e2 --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/AsioDriverInfo.java @@ -0,0 +1,68 @@ +/* + * Copyright 2009 Martin Roth (mhroth@gmail.com) + * + * This file is part of JAsioHost. + * + * JAsioHost is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JAsioHost 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with JAsioHost. If not, see . + * + */ + +package com.synthbot.jasiohost; + +/** + * This is a protected class meant only to encapsulate the returned values from + * AsioDriver.ASIOInit(). + */ +public class AsioDriverInfo { + + private final int asioVersion; + private final int driverVersion; + private final String driverName; + private final String errorMessage; + + protected AsioDriverInfo(int asioVersion, int driverVersion, String driverName, String errorMessage) { + this.asioVersion = asioVersion; + this.driverVersion = driverVersion; + this.driverName = driverName; + this.errorMessage = errorMessage; + } + + public int getAsioVersion() { + return asioVersion; + } + + public int getDriverVersion() { + return driverVersion; + } + + public String getDriverName() { + return driverName; + } + + public String getErrorMessage() { + return errorMessage; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("=== ASIO Driver Information ===\n"); + sb.append("ASIO Version: "); sb.append(Integer.toString(asioVersion)); sb.append("\n"); + sb.append("Driver Version: "); sb.append(Integer.toString(driverVersion)); sb.append("\n"); + sb.append("Driver Name: "); sb.append(driverName); sb.append("\n"); + sb.append("Error Message: "); sb.append(errorMessage); + return sb.toString(); + } + +} diff --git a/jasiohost-master/src/com/synthbot/jasiohost/AsioDriverListener.java b/jasiohost-master/src/com/synthbot/jasiohost/AsioDriverListener.java new file mode 100644 index 0000000..d0ae360 --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/AsioDriverListener.java @@ -0,0 +1,88 @@ +/* + * Copyright 2009 Martin Roth (mhroth@gmail.com) + * + * This file is part of JAsioHost. + * + * JAsioHost is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JAsioHost 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with JAsioHost. If not, see . + * + */ + +package com.synthbot.jasiohost; + +import java.util.Set; + +/** + * This interface defines the callbacks that an ASIO driver may make to the host. + */ +public interface AsioDriverListener { + + /** + * The sample rate has changed. This may be due to a user initiated change, or a change in input/output + * source. + * @param sampleRate The new sample rate. + */ + public void sampleRateDidChange(double sampleRate); + + /** + * The driver requests a reset in the case of an unexpected failure or a device + * reconfiguration. As this request is being made in a callback, the driver should + * only be reset after this callback method has returned. The recommended way to reset + * the driver is: + *

+   * public void resetRequest() {
+   *   new Thread() {
+   *     @Override
+   *     public void run() {
+   * 	     AsioDriver.getDriver().returnToState(AsioDriverState.INITIALIZED);
+   *     }
+   *   }.start();
+   * }
+   * 
+ * Because all methods are synchronized, this approach will safely return the driver + * to the INITIALIZED state as soon as possible. The buffers must then be recreated + * and the driver restarted. + */ + public void resetRequest(); + + /** + * The driver detected audio buffer underruns and requires a resynchronization. + */ + public void resyncRequest(); + + /** + * The driver has a new preferred buffer size. The host should make an effort to + * accommodate the driver by returning to the INITIALIZED state and calling + * AsioDriver.createBuffers(). + * @param bufferSize The new preferred buffer size. + */ + public void bufferSizeChanged(int bufferSize); + + /** + * The input or output latencies have changed. The host is updated with the new values. + * @param inputLatency The new input latency in milliseconds. + * @param outputLatency The new output latency in milliseconds. + */ + public void latenciesChanged(int inputLatency, int outputLatency); + + /** + * The next block of samples is ready. Input buffers are filled with new input, + * and output buffers should be filled at the end of this method. + * @param sampleTime System time related to sample position, in nanoseconds. + * @param samplePosition Sample position since start() was called. + * @param activeChannels The set of channels which are active and have allocated buffers. Retrieve + * the buffers with AsioChannel.getBuffer(), or use AsioChannel.read() + * and AsioDriver.write() in order to easily work with float arrays. + */ + public void bufferSwitch(long sampleTime, long samplePosition, Set activeChannels); +} diff --git a/jasiohost-master/src/com/synthbot/jasiohost/AsioDriverState.java b/jasiohost-master/src/com/synthbot/jasiohost/AsioDriverState.java new file mode 100644 index 0000000..c25c89a --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/AsioDriverState.java @@ -0,0 +1,50 @@ +/* + * Copyright 2009 Martin Roth (mhroth@gmail.com) + * + * This file is part of JAsioHost. + * + * JAsioHost is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JAsioHost 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with JAsioHost. If not, see . + * + */ + +package com.synthbot.jasiohost; + +public enum AsioDriverState { + /** + * The driver is not loaded into memory. It is non-functional. Once a driver is in the + * UNLOADED state, it can not be changed. Use AsioDriver.getDriver(String) + * in order to instantiate a new AsioDriver. + */ + UNLOADED, + + /** + * The driver is loaded into memory. + */ + LOADED, + + /** + * The driver it initialised and is ready to accept commands. + */ + INITIALIZED, + + /** + * The audio buffers have been created and configured. + */ + PREPARED, + + /** + * The driver is running and making calls to AsioDriver.bufferSwitch(). + */ + RUNNING; +} diff --git a/jasiohost-master/src/com/synthbot/jasiohost/AsioException.java b/jasiohost-master/src/com/synthbot/jasiohost/AsioException.java new file mode 100644 index 0000000..b7a3b63 --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/AsioException.java @@ -0,0 +1,35 @@ +/* + * Copyright 2009 Martin Roth (mhroth@gmail.com) + * + * This file is part of JAsioHost. + * + * JAsioHost is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JAsioHost 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with JAsioHost. If not, see . + * + */ + +package com.synthbot.jasiohost; + +/** + * This exception is thrown when something goes wrong while performing a native operation to the + * ASIO driver. This may include loading or unload the driver, or also while managing its operation. + */ +public class AsioException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + protected AsioException(String message) { + super(message); + } + +} diff --git a/jasiohost-master/src/com/synthbot/jasiohost/AsioSampleType.java b/jasiohost-master/src/com/synthbot/jasiohost/AsioSampleType.java new file mode 100644 index 0000000..6900bff --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/AsioSampleType.java @@ -0,0 +1,106 @@ +/* + * Copyright 2009 Martin Roth (mhroth@gmail.com) + * + * This file is part of JAsioHost. + * + * JAsioHost is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JAsioHost 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with JAsioHost. If not, see . + * + */ + +package com.synthbot.jasiohost; + +/** + * This class enumerates the different types of sample formats supported by ASIO. + * The API makes a distinction between Big-Endian (denoted by MSB) and + * Little-Endian (LSB) encodings, which are meaningless in Java, as all + * numbers are Big-Endian encoded. AsioSampleTypes are exposed for informative + * purposes, however they are most useful for determining the Java native type to use. + * The endianness of the sample is resolved in the native library. + */ +public enum AsioSampleType { + + /** + * 16-bit data word + */ + ASIOSTInt16MSB(0), + + /** + * This is the packed 24 bit format. 2 data words will spawn consecutive 6 bytes in memory. + * (Used for 18 and 20 bits as well, if they use this packed format). In Java it is represented + * the same as any of the ASIOSTInt32MSB16 formats. + */ + ASIOSTInt24MSB(1), + + /** + * 32-bit data word. + */ + ASIOSTInt32MSB(2), + + /** + * IEEE 754 32 bit float, as found on Intel x86 architecture. + */ + ASIOSTFloat32MSB(3), + + /** + * IEEE 754 64 bit double float, as found on Intel x86 architecture + */ + ASIOSTFloat64MSB(4), + + /** + * Sample data fills the least significant 16 bits, the other bits are sign extended. + */ + ASIOSTInt32MSB16(8), + + /** + * Sample data fills the least significant 18 bits, the other bits are sign extended. + */ + ASIOSTInt32MSB18(9), + + /** + * Sample data fills the least significant 20 bits, the other bits are sign extended. + */ + ASIOSTInt32MSB20(10), + + /** + * Sample data fills the least significant 24 bits, the other bits are sign extended. + */ + ASIOSTInt32MSB24(11), + ASIOSTInt16LSB(16), + ASIOSTInt24LSB(17), + ASIOSTInt32LSB(18), + ASIOSTFloat32LSB(19), + ASIOSTFloat64LSB(20), + ASIOSTInt32LSB16(24), + ASIOSTInt32LSB18(25), + ASIOSTInt32LSB20(26), + ASIOSTInt32LSB24(27), + ASIOSTDSDInt8LSB1(32), + ASIOSTDSDInt8MSB1(33), + ASIOSTDSDInt8NER8(40); + + private int nativeEnum; // the native enum representing this type + + private AsioSampleType(int nativeEnum) { + this.nativeEnum = nativeEnum; + } + + public static AsioSampleType getSampleType(int nativeEnum) { + for (AsioSampleType sampleType : values()) { + if (sampleType.nativeEnum == nativeEnum) { + return sampleType; + } + } + return null; + } +} diff --git a/jasiohost-master/src/com/synthbot/jasiohost/ExampleHost.java b/jasiohost-master/src/com/synthbot/jasiohost/ExampleHost.java new file mode 100644 index 0000000..6812d1e --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/ExampleHost.java @@ -0,0 +1,170 @@ +/* + * Copyright 2009,2010 Martin Roth (mhroth@gmail.com) + * + * This file is part of JAsioHost. + * + * JAsioHost is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JAsioHost 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with JAsioHost. If not, see . + * + */ + +package com.synthbot.jasiohost; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.HashSet; +import java.util.Set; + +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.WindowConstants; + +/** + * The ExampleHost demonstrates how to use an AsioDriver in order to read + * and write audio from a loaded ASIO driver. A small GUI is presented, allowing the user to select + * any of the available ASIO drivers on the system. The Start button loads the driver and + * plays a 440Hz tone. The Stop button stops this process and unloads the driver. The + * Control Panel button opens the driver's control panel for any additional configuration. + */ +public class ExampleHost extends JFrame implements AsioDriverListener { + + private static final long serialVersionUID = 1L; + + private AsioDriver asioDriver; + private Set activeChannels; + private int sampleIndex; + private int bufferSize; + private double sampleRate; + private float[] output; + + public ExampleHost() { + super("JAsioHost Example"); + + activeChannels = new HashSet(); + + final JComboBox comboBox = new JComboBox(AsioDriver.getDriverNames().toArray()); + final JButton buttonStart = new JButton("Start"); + final JButton buttonStop = new JButton("Stop"); + final JButton buttonControlPanel = new JButton("Control Panel"); + + final AsioDriverListener host = this; + buttonStart.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { + if (asioDriver == null) { + asioDriver = AsioDriver.getDriver(comboBox.getSelectedItem().toString()); + asioDriver.addAsioDriverListener(host); + activeChannels.add(asioDriver.getChannelOutput(0)); + activeChannels.add(asioDriver.getChannelOutput(1)); + sampleIndex = 0; + bufferSize = asioDriver.getBufferPreferredSize(); + sampleRate = asioDriver.getSampleRate(); + output = new float[bufferSize]; + asioDriver.createBuffers(activeChannels); + asioDriver.start(); + } + } + }); + + buttonStop.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { + if (asioDriver != null) { + asioDriver.shutdownAndUnloadDriver(); + activeChannels.clear(); + asioDriver = null; + } + } + }); + + buttonControlPanel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { + if (asioDriver != null && + asioDriver.getCurrentState().ordinal() >= AsioDriverState.INITIALIZED.ordinal()) { + asioDriver.openControlPanel(); + } + } + }); + + this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS)); + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); + this.add(comboBox); + panel.add(buttonStart); + panel.add(buttonStop); + panel.add(buttonControlPanel); + this.add(panel); + + this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + this.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent event) { + if (asioDriver != null) { + asioDriver.shutdownAndUnloadDriver(); + } + } + }); + + this.setSize(240, 85); + this.setResizable(false); + this.setVisible(true); + } + + public void bufferSwitch(long systemTime, long samplePosition, Set channels) { + for (int i = 0; i < bufferSize; i++, sampleIndex++) { + output[i] = (float) Math.sin(2 * Math.PI * sampleIndex * 440.0 / sampleRate); + } + for (AsioChannel channelInfo : channels) { + channelInfo.write(output); + } + } + + public void bufferSizeChanged(int bufferSize) { + System.out.println("bufferSizeChanged() callback received."); + } + + public void latenciesChanged(int inputLatency, int outputLatency) { + System.out.println("latenciesChanged() callback received."); + } + + public void resetRequest() { + /* + * This thread will attempt to shut down the ASIO driver. However, it will + * block on the AsioDriver object at least until the current method has returned. + */ + new Thread() { + @Override + public void run() { + System.out.println("resetRequest() callback received. Returning driver to INITIALIZED state."); + asioDriver.returnToState(AsioDriverState.INITIALIZED); + } + }.start(); + } + + public void resyncRequest() { + System.out.println("resyncRequest() callback received."); + } + + public void sampleRateDidChange(double sampleRate) { + System.out.println("sampleRateDidChange() callback received."); + } + + public static void main(String[] args) { + @SuppressWarnings("unused") + ExampleHost host = new ExampleHost(); + } + +} diff --git a/jasiohost-master/src/com/synthbot/jasiohost/JAsioHost.cpp b/jasiohost-master/src/com/synthbot/jasiohost/JAsioHost.cpp new file mode 100644 index 0000000..9f3ea50 --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/JAsioHost.cpp @@ -0,0 +1,744 @@ +/* + * Copyright 2009,2010 Martin Roth (mhroth@gmail.com) + * + * This file is part of JAsioHost. + * + * JAsioHost is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * JAsioHost 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with JAsioHost. If not, see . + * + */ + +#include +#include +#include +#include "asiosys.h" +#include "asio.h" +#include "asiodrivers.h" +#include "iasiothiscallresolver.h" +#include "com_synthbot_jasiohost_AsioDriver.h" + +#define JNI_VERSION JNI_VERSION_1_4 + +// external reference +extern AsioDrivers* asioDrivers; + +// global variables +JavaVM *jvm; +jobject jAsioDriver; // a strong global reference to the AsioDriver Java object for use in callbacks + +// global references to the callback methods +jmethodID fireBufferSwitchMid; +jmethodID fireLatenciesChangedMid; +jmethodID fireResetRequestMid; +jmethodID fireSampleRateDidChangeMid; +jmethodID fireResyncRequestMid; +jmethodID fireBufferSizeChangedMid; + +typedef struct BufferVars { + ASIOBufferInfo *bufferInfos; + int numInitedChannels; // length of bufferInfos array + int bufferSize; + ASIOCallbacks *callbacks; + long samplePosition; +}; +BufferVars bufferVars = {0}; + +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *localJvm, void *reserved) { + jvm = localJvm; // store the JVM so that it can be used to attach ASIO threads to the JVM during callbacks + asioDrivers = new AsioDrivers(); // set the global variable + + JNIEnv *env = NULL; + jvm->GetEnv((void **) &env, JNI_VERSION); + + // assign global references to callback methods + fireBufferSwitchMid = env->GetMethodID( + env->FindClass("com/synthbot/jasiohost/AsioDriver"), + "fireBufferSwitch", "(JJI)V"); + fireLatenciesChangedMid = env->GetMethodID( + env->FindClass("com/synthbot/jasiohost/AsioDriver"), + "fireLatenciesChanged", "(II)V"); + fireResetRequestMid = env->GetMethodID( + env->FindClass("com/synthbot/jasiohost/AsioDriver"), + "fireResetRequest", "()V"); + fireSampleRateDidChangeMid = env->GetMethodID( + env->FindClass("com/synthbot/jasiohost/AsioDriver"), + "fireSampleRateDidChange", "(D)V"); + fireResyncRequestMid = env->GetMethodID( + env->FindClass("com/synthbot/jasiohost/AsioDriver"), + "fireResyncRequest", "()V"); + fireBufferSizeChangedMid = env->GetMethodID( + env->FindClass("com/synthbot/jasiohost/AsioDriver"), + "fireBufferSizeChanged", "(I)V"); + + jAsioDriver = NULL; + + return JNI_VERSION; +} + +JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *jvm, void *reserved) { + if (asioDrivers) { + delete asioDrivers; + } +} + +#if NATIVE_INT64 + #define ASIO64toLong(a) (a) +#else + #define ASIO64toLong(a) (((unsigned long long int) a.hi) << 32) | (unsigned long long int) a.lo +#endif + + +/* + * Driver Callbacks + */ + +// from ASIOv2 +ASIOTime* bufferSwitchTimeInfo(ASIOTime* asioTime, long bufferIndex, ASIOBool directProcess) { + JNIEnv *env = NULL; + jint res = jvm->AttachCurrentThreadAsDaemon((void **) &env, NULL); + if (res == JNI_OK && env != NULL) { + env->CallVoidMethod( + jAsioDriver, + fireBufferSwitchMid, + (jlong) ASIO64toLong(asioTime->timeInfo.systemTime), + (jlong) ASIO64toLong(asioTime->timeInfo.samplePosition), + (jint) bufferIndex); + } + + ASIOOutputReady(); + + return asioTime; +} + +// from ASIOv1 +void bufferSwitch(long bufferIndex, ASIOBool directProcess) { + ASIOTime asioTime = {0}; + ASIOError errorCode = ASIOGetSamplePosition(&asioTime.timeInfo.samplePosition, &asioTime.timeInfo.systemTime); + if (errorCode == ASE_OK) { + asioTime.timeInfo.flags = kSystemTimeValid | kSamplePositionValid; + } + bufferSwitchTimeInfo(&asioTime, bufferIndex, directProcess); +} + +void sampleRateDidChange(ASIOSampleRate sampleRate) { + JNIEnv *env = NULL; + jint res = jvm->AttachCurrentThreadAsDaemon((void **) &env, NULL); + if (res == JNI_OK && env != NULL) { + env->CallVoidMethod( + jAsioDriver, + fireSampleRateDidChangeMid, + (jdouble) sampleRate); + } +} +long asioMessage(long selector, long value, void* message, double* opt) { + switch (selector) { + case kAsioSelectorSupported: { + switch (value) { + case kAsioEngineVersion: + case kAsioResetRequest: + case kAsioResyncRequest: + case kAsioBufferSizeChange: + case kAsioLatenciesChanged: + case kAsioSupportsTimeInfo: + case kAsioSupportsTimeCode: { + return 1L; + } + default: { + // no supporting kAsioSupportsInputMonitor yet because I don't know what it is + return 0L; + } + } + } + + case kAsioEngineVersion: { + return 2L; + } + + case kAsioResetRequest: { + JNIEnv *env = NULL; + jint res = jvm->AttachCurrentThreadAsDaemon((void **) &env, NULL); + if (res == JNI_OK && env != NULL) { + env->CallVoidMethod( + jAsioDriver, + fireResetRequestMid); + } + return 1L; + } + + case kAsioResyncRequest: { + JNIEnv *env = NULL; + jint res = jvm->AttachCurrentThreadAsDaemon((void **) &env, NULL); + if (res == JNI_OK && env != NULL) { + env->CallVoidMethod( + jAsioDriver, + fireResyncRequestMid); + } + return 1L; + } + + case kAsioBufferSizeChange: { + JNIEnv *env = NULL; + jint res = jvm->AttachCurrentThreadAsDaemon((void **) &env, NULL); + if (res == JNI_OK && env != NULL) { + env->CallVoidMethod( + jAsioDriver, + fireBufferSizeChangedMid, + (jint) value); + } + return 1L; // the request is always accepted + } + + case kAsioLatenciesChanged: { + JNIEnv *env = NULL; + jint res = jvm->AttachCurrentThreadAsDaemon((void **) &env, NULL); + if (res == JNI_OK && env != NULL) { + env->CallVoidMethod( + jAsioDriver, + fireLatenciesChangedMid, + Java_com_synthbot_jasiohost_AsioDriver_ASIOGetLatencies(env, NULL, JNI_TRUE), + Java_com_synthbot_jasiohost_AsioDriver_ASIOGetLatencies(env, NULL, JNI_FALSE)); + } + return 1L; + } + + case kAsioSupportsTimeInfo: { + return 1L; + } + + case kAsioSupportsTimeCode: { + return 0L; + } + + default: { + return 0L; + } + } +} + + +/* + * JAsioHost + */ + +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_registerThread +(JNIEnv *env, jclass clazz) { + + CoInitialize(NULL); +} + +JNIEXPORT jboolean JNICALL Java_com_synthbot_jasiohost_AsioDriver_loadDriver +(JNIEnv *env, jclass clazz, jstring jdriverName) { + + char *driverName = (char *) env->GetStringUTFChars(jdriverName, NULL); + bool isLoaded = asioDrivers->loadDriver(driverName); + env->ReleaseStringUTFChars(jdriverName, driverName); + return isLoaded ? JNI_TRUE : JNI_FALSE; +} + +JNIEXPORT jobject JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOInit +(JNIEnv *env, jobject jobj) { + + ASIODriverInfo asioDriverInfo = {0}; + asioDriverInfo.asioVersion = 2L; + ASIOError errorCode = ASIOInit(&asioDriverInfo); + if (errorCode == ASE_OK) { + jAsioDriver = env->NewGlobalRef(jobj); // store global ref to AsioDriver object for callbacks + + // create new AsioDriverInfo object and return it + return env->NewObject( + env->FindClass("com/synthbot/jasiohost/AsioDriverInfo"), + env->GetMethodID(env->FindClass("com/synthbot/jasiohost/AsioDriverInfo"), "", "(IILjava/lang/String;Ljava/lang/String;)V"), + asioDriverInfo.asioVersion, + asioDriverInfo.driverVersion, + env->NewStringUTF(asioDriverInfo.name), + env->NewStringUTF(asioDriverInfo.errorMessage)); + } else { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + asioDriverInfo.errorMessage); + return NULL; + } +} + +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOExit +(JNIEnv *env, jobject jobj) { + + env->DeleteGlobalRef(jAsioDriver); + jAsioDriver = NULL; + ASIOExit(); +} + +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_removeCurrentDriver +(JNIEnv *env, jclass clazz) { + + asioDrivers->removeCurrentDriver(); +} + +JNIEXPORT jint JNICALL Java_com_synthbot_jasiohost_AsioDriver_getDriverNames +(JNIEnv *env, jclass clazz, jobjectArray jdriverNames) { + + long maxNames = (long) env->GetArrayLength(jdriverNames); + char **names = (char **) malloc(sizeof(char *) * maxNames); + for (int i = 0; i < maxNames; i++) { + names[i] = (char *) malloc(sizeof(char) * 32); + } + + long numNames = asioDrivers->getDriverNames(names, maxNames); + for (int i = 0; i < numNames; i++) { + env->SetObjectArrayElement(jdriverNames, i, env->NewStringUTF(names[i])); + } + + for(int i = 0; i < maxNames; i++) { + free(names[i]); + } + free(names); + + return (jint) numNames; +} + +/** + * Deprecated in Java + * +JNIEXPORT jint JNICALL Java_com_synthbot_jasiohost_AsioDriver_getCurrentDriverIndex +(JNIEnv *env, jclass clazz) { + + return (jint) asioDrivers->getCurrentDriverIndex(); +} + */ + +/** + * Deprecated in Java + * +JNIEXPORT jstring JNICALL Java_com_synthbot_jasiohost_AsioDriver_getCurrentDriverName +(JNIEnv *env, jclass clazz) { + + char *name = (char *) malloc(sizeof(char) * 32); + asioDrivers->getCurrentDriverName(name); + jstring jname = env->NewStringUTF(name); + free(name); + return jname; +} + */ + + +/* + * AsioDriver + */ + +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOControlPanel +(JNIEnv *env, jclass clazz) { + + ASIOControlPanel(); +} + +JNIEXPORT jint JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOGetChannels +(JNIEnv *env, jclass clazz, jboolean isInput) { + + long numInputs; + long numOutputs; + ASIOError errorCode = ASIOGetChannels(&numInputs, &numOutputs); + if (errorCode == ASE_OK) { + return (isInput == JNI_TRUE) ? (jint) numInputs : (jint) numOutputs; + } else { + return (jint) 0; + } +} + +JNIEXPORT jdouble JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOGetSampleRate +(JNIEnv *env, jclass clazz) { + + ASIOSampleRate sampleRate; + ASIOError errorCode = ASIOGetSampleRate(&sampleRate); + switch (errorCode) { + case ASE_OK: { + return (jdouble) sampleRate; + } + case ASE_NoClock: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "Sample rate not present or unknown."); + return (jdouble) -1.0; + } + case ASE_NotPresent: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "No input or output is present."); + return (jdouble) -1.0; + } + } +} + +JNIEXPORT jboolean JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOCanSampleRate +(JNIEnv *env, jclass clazz, jdouble sampleRate) { + + ASIOError errorCode = ASIOCanSampleRate((ASIOSampleRate) sampleRate); + return (errorCode == ASE_OK) ? JNI_TRUE : JNI_FALSE; +} + +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOSetSampleRate +(JNIEnv *env, jclass clazz, jdouble sampleRate) { + + ASIOError errorCode = ASIOSetSampleRate((ASIOSampleRate) sampleRate); + switch (errorCode) { + case ASE_OK: { + return; + } + case ASE_NoClock: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "Sample rate not present or unknown."); + } + case ASE_InvalidMode: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "The current clock is external and the given sample rate is non-zero."); + } + case ASE_NotPresent: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "No input or output is present."); + } + } +} + +JNIEXPORT jint JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOGetBufferSize +(JNIEnv *env, jclass clazz, jint argIndex) { + + long minSize; + long maxSize; + long preferredSize; + long granularity; + ASIOError errorCode = ASIOGetBufferSize(&minSize, &maxSize, &preferredSize, &granularity); + if (errorCode == ASE_OK) { + switch (argIndex) { + case 0: { + return (jint) minSize; + } + case 1: { + return (jint) maxSize; + } + case 2: { + return (jint) preferredSize; + } + case 3: { + return (jint) granularity; + } + default: { + return -1; + } + } + } else { + return -1; + } +} + +JNIEXPORT jint JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOGetLatencies +(JNIEnv *env, jclass clazz, jboolean isInput) { + + long inputLatency; + long outputLatency; + ASIOError errorCode = ASIOGetLatencies(&inputLatency, &outputLatency); + switch (errorCode) { + case ASE_OK: { + // normal operation + return (isInput == JNI_TRUE) ? (jint) inputLatency : (jint) outputLatency; + } + case ASE_NotPresent: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + (isInput == JNI_TRUE) ? "The requested input does not exist." : "The requested output does not exist."); + return (jint) 0; + } + default: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "Unknown error code."); + return (jint) 0; + } + } +} + +JNIEXPORT jobject JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOGetChannelInfo +(JNIEnv *env, jclass clazz, jint index, jboolean isInput) { + + ASIOChannelInfo channelInfo; + channelInfo.channel = (long) index; + channelInfo.isInput = (isInput == JNI_TRUE) ? ASIOTrue : ASIOFalse; + ASIOError errorCode = ASIOGetChannelInfo(&channelInfo); + + switch (errorCode) { + case ASE_OK: { + return env->NewObject( + env->FindClass("com/synthbot/jasiohost/AsioChannel"), + env->GetMethodID(env->FindClass("com/synthbot/jasiohost/AsioChannel"), "", "(IZZILcom/synthbot/jasiohost/AsioSampleType;Ljava/lang/String;)V"), + (jint) index, + isInput, + (channelInfo.isActive == ASIOTrue) ? JNI_TRUE : JNI_FALSE, + (jint) channelInfo.channelGroup, + env->CallStaticObjectMethod( + env->FindClass("com/synthbot/jasiohost/AsioSampleType"), + env->GetStaticMethodID(env->FindClass("com/synthbot/jasiohost/AsioSampleType"), "getSampleType", "(I)Lcom/synthbot/jasiohost/AsioSampleType;"), + channelInfo.type), + env->NewStringUTF(channelInfo.name)); + } + case ASE_NotPresent: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + (isInput == JNI_TRUE) ? "The requested input does not exist." : "The requested output does not exist."); + return NULL; + } + default: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "Unknown error code."); + return NULL; + } + } +} + +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOCreateBuffers +(JNIEnv *env, jclass clazz, jobjectArray channelsToInit, jint bufferSize) { + + bufferVars.numInitedChannels = (int) env->GetArrayLength(channelsToInit); + bufferVars.bufferInfos = (ASIOBufferInfo *) malloc(sizeof(ASIOBufferInfo) * bufferVars.numInitedChannels); + std::vector sampleTypes(bufferVars.numInitedChannels); + for (int i = 0; i < bufferVars.numInitedChannels; i++) { + jobject channelInfo = env->GetObjectArrayElement(channelsToInit, (jsize) i); + jboolean jIsInput = env->CallBooleanMethod(channelInfo, + env->GetMethodID(env->FindClass("com/synthbot/jasiohost/AsioChannel"), "isInput", "()Z")); + bufferVars.bufferInfos[i].isInput = (jIsInput == JNI_TRUE) ? ASIOTrue : ASIOFalse; + jint channelNum = env->CallIntMethod(channelInfo, + env->GetMethodID(env->FindClass("com/synthbot/jasiohost/AsioChannel"), "getChannelIndex", "()I")); + bufferVars.bufferInfos[i].channelNum = (long) channelNum; + sampleTypes[i] = env->GetIntField(env->CallObjectMethod( + channelInfo, + env->GetMethodID(env->FindClass("com/synthbot/jasiohost/AsioChannel"), "getSampleType", "()Lcom/synthbot/jasiohost/AsioSampleType;")), + env->GetFieldID(env->FindClass("com/synthbot/jasiohost/AsioSampleType"), "nativeEnum", "I")); + } + + bufferVars.bufferSize = (int) bufferSize; + + bufferVars.callbacks = (ASIOCallbacks *) malloc(sizeof(ASIOCallbacks)); + bufferVars.callbacks->bufferSwitch = &bufferSwitch; + bufferVars.callbacks->sampleRateDidChange = &sampleRateDidChange; + bufferVars.callbacks->asioMessage = &asioMessage; + bufferVars.callbacks->bufferSwitchTimeInfo = &bufferSwitchTimeInfo; + + ASIOError errorCode = ASIOCreateBuffers(bufferVars.bufferInfos, (long) bufferVars.numInitedChannels, (long) bufferVars.bufferSize, bufferVars.callbacks); + + switch (errorCode) { + case ASE_OK: { + for (int i = 0; i < bufferVars.numInitedChannels; i++) { + jobject byteBuffer0 = NULL; + jobject byteBuffer1 = NULL; + switch (sampleTypes[i]) { + case ASIOSTFloat64MSB: + case ASIOSTFloat64LSB: { + if (bufferVars.bufferInfos[i].buffers[0] != NULL && + bufferVars.bufferInfos[i].buffers[1] != NULL) { + byteBuffer0 = env->NewDirectByteBuffer(bufferVars.bufferInfos[i].buffers[0], bufferSize * 8); + byteBuffer1 = env->NewDirectByteBuffer(bufferVars.bufferInfos[i].buffers[1], bufferSize * 8); + } + break; + } + case ASIOSTFloat32MSB: + case ASIOSTFloat32LSB: + case ASIOSTInt32MSB: + case ASIOSTInt32MSB16: + case ASIOSTInt32MSB18: + case ASIOSTInt32MSB20: + case ASIOSTInt32MSB24: + case ASIOSTInt32LSB: + case ASIOSTInt32LSB16: + case ASIOSTInt32LSB18: + case ASIOSTInt32LSB20: + case ASIOSTInt32LSB24: { + if (bufferVars.bufferInfos[i].buffers[0] != NULL && + bufferVars.bufferInfos[i].buffers[1] != NULL) { + byteBuffer0 = env->NewDirectByteBuffer(bufferVars.bufferInfos[i].buffers[0], bufferSize * 4); + byteBuffer1 = env->NewDirectByteBuffer(bufferVars.bufferInfos[i].buffers[1], bufferSize * 4); + } + break; + } + case ASIOSTInt24MSB: + case ASIOSTInt24LSB: { + if (bufferVars.bufferInfos[i].buffers[0] != NULL && + bufferVars.bufferInfos[i].buffers[1] != NULL) { + byteBuffer0 = env->NewDirectByteBuffer(bufferVars.bufferInfos[i].buffers[0], bufferSize * 3); + byteBuffer1 = env->NewDirectByteBuffer(bufferVars.bufferInfos[i].buffers[1], bufferSize * 3); + } + break; + } + case ASIOSTInt16MSB: + case ASIOSTInt16LSB: { + if (bufferVars.bufferInfos[i].buffers[0] != NULL && + bufferVars.bufferInfos[i].buffers[1] != NULL) { + byteBuffer0 = env->NewDirectByteBuffer(bufferVars.bufferInfos[i].buffers[0], bufferSize * 2); + byteBuffer1 = env->NewDirectByteBuffer(bufferVars.bufferInfos[i].buffers[1], bufferSize * 2); + } + break; + } + case ASIOSTDSDInt8MSB1: + case ASIOSTDSDInt8LSB1: + case ASIOSTDSDInt8NER8: { + if (bufferVars.bufferInfos[i].buffers[0] != NULL && + bufferVars.bufferInfos[i].buffers[1] != NULL) { + byteBuffer0 = env->NewDirectByteBuffer(bufferVars.bufferInfos[i].buffers[0], bufferSize * 1); + byteBuffer1 = env->NewDirectByteBuffer(bufferVars.bufferInfos[i].buffers[1], bufferSize * 1); + } + break; + } + default: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "Unknown sample type."); + break; + } + } + + if (byteBuffer0 == NULL || byteBuffer1 == NULL) { + if (env->ExceptionCheck() == JNI_TRUE) { + env->Throw(env->ExceptionOccurred()); + return; + } else { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "JNI access to direct buffers is not supported by this virtual machine."); + return; + } + } + env->CallVoidMethod( + env->GetObjectArrayElement(channelsToInit, (jsize) i), + env->GetMethodID( + env->FindClass("com/synthbot/jasiohost/AsioChannel"), + "setByteBuffers", "(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V"), + byteBuffer0, + byteBuffer1); + } + return; + } + case ASE_NoMemory: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "Not enough memory is available for the audio buffers to be created."); + return; + } + case ASE_NotPresent: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "No input or output is present."); + return; + } + case ASE_InvalidMode: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "The buffer size is not supported."); + return; + } + default: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "Unknown error code."); + return; + } + } +} + +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIODisposeBuffers +(JNIEnv *env, jclass clazz) { + + free(bufferVars.bufferInfos); + free(bufferVars.callbacks); + + ASIOError errorCode = ASIODisposeBuffers(); + + switch (errorCode) { + case ASE_OK: { + // normal operation + return; + } + case ASE_InvalidMode: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "No buffers to dispose of. None were ever created."); + return; + } + case ASE_NotPresent: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "No input or output is present."); + return; + } + default: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "Unknown error code."); + } + } +} + +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOStart +(JNIEnv *env, jclass clazz) { + + ASIOError errorCode = ASIOStart(); + + switch (errorCode) { + case ASE_OK: { + // normal operation + return; + } + case ASE_NotPresent: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "No input or output is present."); + return; + } + case ASE_HWMalfunction: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "The hardware has malfunctioned."); + return; + } + default: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "Unknown error code."); + return; + } + } +} + +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOStop +(JNIEnv *env, jclass clazz) { + + ASIOError errorCode = ASIOStop(); + + switch (errorCode) { + case ASE_OK: { + // normal operation + return; + } + case ASE_NotPresent: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "No input or output is present."); + return; + } + default: { + env->ThrowNew( + env->FindClass("com/synthbot/jasiohost/AsioException"), + "Unknown error code."); + return; + } + } +} \ No newline at end of file diff --git a/jasiohost-master/src/com/synthbot/jasiohost/buildJah64_win.sh b/jasiohost-master/src/com/synthbot/jasiohost/buildJah64_win.sh new file mode 100644 index 0000000..a5e2d22 --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/buildJah64_win.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +x86_64-w64-mingw32-g++ -mno-cygwin -D__int64="long long" -o jasiohost64.dll -static -shared -O3 -W -Wl,--add-stdcall-alias \ +-I. \ +-I/cygdrive/c/Program\ Files/Java/jdk1.6.0_31/include \ +-I/cygdrive/c/Program\ Files/Java/jdk1.6.0_31/include/win32 \ +-I./ASIOSDK2/common \ +-I./ASIOSDK2/host \ +-I./ASIOSDK2/host/pc \ +./JAsioHost.cpp \ +./ASIOSDK2/common/*.cpp \ +./ASIOSDK2/host/*.cpp \ +./ASIOSDK2/host/pc/*.cpp \ +-lstdc++ -lole32 -luuid + +ls -l jasiohost.dll \ No newline at end of file diff --git a/jasiohost-master/src/com/synthbot/jasiohost/buildJah_win.sh b/jasiohost-master/src/com/synthbot/jasiohost/buildJah_win.sh new file mode 100644 index 0000000..ce81ee0 --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/buildJah_win.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +gcc -mno-cygwin -D__int64="long long" -o jasiohost.dll -shared -O3 -w -Wl,--add-stdcall-alias \ +-I. \ +-I/cygdrive/c/Java/jdk1.6.0_12/include \ +-I/cygdrive/c/Java/jdk1.6.0_12/include/win32 \ +-I./ASIOSDK2/common \ +-I./ASIOSDK2/host \ +-I./ASIOSDK2/host/pc \ +./*.cpp \ +./ASIOSDK2/common/*.cpp \ +./ASIOSDK2/host/*.cpp \ +./ASIOSDK2/host/pc/*.cpp \ +-lstdc++ -lole32 -luuid + +ls -l jasiohost.dll +echo copying jasiohost.dll to C:/WINDOWS/system32 +cp jasiohost.dll /cygdrive/c/WINDOWS/system32 +mv jasiohost.dll ../../../../ \ No newline at end of file diff --git a/jasiohost-master/src/com/synthbot/jasiohost/build_hostsample.sh b/jasiohost-master/src/com/synthbot/jasiohost/build_hostsample.sh new file mode 100644 index 0000000..00de0c3 --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/build_hostsample.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +gcc -mno-cygwin -D__int64="long long" -o jasiohost.exe -O3 -w -Wl,--add-stdcall-alias \ +-I. \ +-I/cygdrive/c/Java/jdk1.6.0_12/include \ +-I/cygdrive/c/Java/jdk1.6.0_12/include/win32 \ +-I. \ +-I./ASIOSDK2/common \ +-I./ASIOSDK2/host \ +-I./ASIOSDK2/host/sample \ +-I./ASIOSDK2/host/pc \ +./iasiothiscallresolver.cpp \ +./ASIOSDK2/common/*.cpp \ +./ASIOSDK2/host/*.cpp \ +./ASIOSDK2/host/sample/*.cpp \ +./ASIOSDK2/host/pc/*.cpp \ +-lstdc++ -lole32 -luuid -lwinmm +#-I/usr/include \ + +ls -l jasiohost.exe \ No newline at end of file diff --git a/jasiohost-master/src/com/synthbot/jasiohost/com_synthbot_jasiohost_AsioDriver.h b/jasiohost-master/src/com/synthbot/jasiohost/com_synthbot_jasiohost_AsioDriver.h new file mode 100644 index 0000000..2e86bef --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/com_synthbot_jasiohost_AsioDriver.h @@ -0,0 +1,157 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class com_synthbot_jasiohost_AsioDriver */ + +#ifndef _Included_com_synthbot_jasiohost_AsioDriver +#define _Included_com_synthbot_jasiohost_AsioDriver +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: registerThread + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_registerThread + (JNIEnv *, jclass); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: getDriverNames + * Signature: ([Ljava/lang/String;)I + */ +JNIEXPORT jint JNICALL Java_com_synthbot_jasiohost_AsioDriver_getDriverNames + (JNIEnv *, jclass, jobjectArray); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOInit + * Signature: ()Lcom/synthbot/jasiohost/AsioDriverInfo; + */ +JNIEXPORT jobject JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOInit + (JNIEnv *, jobject); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOExit + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOExit + (JNIEnv *, jobject); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOControlPanel + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOControlPanel + (JNIEnv *, jclass); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOGetChannels + * Signature: (Z)I + */ +JNIEXPORT jint JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOGetChannels + (JNIEnv *, jclass, jboolean); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOGetSampleRate + * Signature: ()D + */ +JNIEXPORT jdouble JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOGetSampleRate + (JNIEnv *, jclass); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOCanSampleRate + * Signature: (D)Z + */ +JNIEXPORT jboolean JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOCanSampleRate + (JNIEnv *, jclass, jdouble); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOSetSampleRate + * Signature: (D)V + */ +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOSetSampleRate + (JNIEnv *, jclass, jdouble); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOGetBufferSize + * Signature: (I)I + */ +JNIEXPORT jint JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOGetBufferSize + (JNIEnv *, jclass, jint); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOGetLatencies + * Signature: (Z)I + */ +JNIEXPORT jint JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOGetLatencies + (JNIEnv *, jclass, jboolean); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOGetChannelInfo + * Signature: (IZ)Lcom/synthbot/jasiohost/AsioChannel; + */ +JNIEXPORT jobject JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOGetChannelInfo + (JNIEnv *, jclass, jint, jboolean); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOCreateBuffers + * Signature: ([Lcom/synthbot/jasiohost/AsioChannel;I)V + */ +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOCreateBuffers + (JNIEnv *, jclass, jobjectArray, jint); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIODisposeBuffers + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIODisposeBuffers + (JNIEnv *, jclass); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOStart + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOStart + (JNIEnv *, jclass); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: ASIOStop + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_ASIOStop + (JNIEnv *, jclass); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: loadDriver + * Signature: (Ljava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL Java_com_synthbot_jasiohost_AsioDriver_loadDriver + (JNIEnv *, jclass, jstring); + +/* + * Class: com_synthbot_jasiohost_AsioDriver + * Method: removeCurrentDriver + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_com_synthbot_jasiohost_AsioDriver_removeCurrentDriver + (JNIEnv *, jclass); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/jasiohost-master/src/com/synthbot/jasiohost/iasiothiscallresolver.cpp b/jasiohost-master/src/com/synthbot/jasiohost/iasiothiscallresolver.cpp new file mode 100644 index 0000000..38c39d2 --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/iasiothiscallresolver.cpp @@ -0,0 +1,563 @@ +/* + IASIOThiscallResolver.cpp see the comments in iasiothiscallresolver.h for + the top level description - this comment describes the technical details of + the implementation. + + The latest version of this file is available from: + http://www.audiomulch.com/~rossb/code/calliasio + + please email comments to Ross Bencina + + BACKGROUND + + The IASIO interface declared in the Steinberg ASIO 2 SDK declares + functions with no explicit calling convention. This causes MSVC++ to default + to using the thiscall convention, which is a proprietary convention not + implemented by some non-microsoft compilers - notably borland BCC, + C++Builder, and gcc. MSVC++ is the defacto standard compiler used by + Steinberg. As a result of this situation, the ASIO sdk will compile with + any compiler, however attempting to execute the compiled code will cause a + crash due to different default calling conventions on non-Microsoft + compilers. + + IASIOThiscallResolver solves the problem by providing an adapter class that + delegates to the IASIO interface using the correct calling convention + (thiscall). Due to the lack of support for thiscall in the Borland and GCC + compilers, the calls have been implemented in assembly language. + + A number of macros are defined for thiscall function calls with different + numbers of parameters, with and without return values - it may be possible + to modify the format of these macros to make them work with other inline + assemblers. + + + THISCALL DEFINITION + + A number of definitions of the thiscall calling convention are floating + around the internet. The following definition has been validated against + output from the MSVC++ compiler: + + For non-vararg functions, thiscall works as follows: the object (this) + pointer is passed in ECX. All arguments are passed on the stack in + right to left order. The return value is placed in EAX. The callee + clears the passed arguments from the stack. + + + FINDING FUNCTION POINTERS FROM AN IASIO POINTER + + The first field of a COM object is a pointer to its vtble. Thus a pointer + to an object implementing the IASIO interface also points to a pointer to + that object's vtbl. The vtble is a table of function pointers for all of + the virtual functions exposed by the implemented interfaces. + + If we consider a variable declared as a pointer to IASO: + + IASIO *theAsioDriver + + theAsioDriver points to: + + object implementing IASIO + { + IASIOvtbl *vtbl + other data + } + + in other words, theAsioDriver points to a pointer to an IASIOvtbl + + vtbl points to a table of function pointers: + + IASIOvtbl ( interface IASIO : public IUnknown ) + { + (IUnknown functions) + 0 virtual HRESULT STDMETHODCALLTYPE (*QueryInterface)(REFIID riid, void **ppv) = 0; + 4 virtual ULONG STDMETHODCALLTYPE (*AddRef)() = 0; + 8 virtual ULONG STDMETHODCALLTYPE (*Release)() = 0; + + (IASIO functions) + 12 virtual ASIOBool (*init)(void *sysHandle) = 0; + 16 virtual void (*getDriverName)(char *name) = 0; + 20 virtual long (*getDriverVersion)() = 0; + 24 virtual void (*getErrorMessage)(char *string) = 0; + 28 virtual ASIOError (*start)() = 0; + 32 virtual ASIOError (*stop)() = 0; + 36 virtual ASIOError (*getChannels)(long *numInputChannels, long *numOutputChannels) = 0; + 40 virtual ASIOError (*getLatencies)(long *inputLatency, long *outputLatency) = 0; + 44 virtual ASIOError (*getBufferSize)(long *minSize, long *maxSize, + long *preferredSize, long *granularity) = 0; + 48 virtual ASIOError (*canSampleRate)(ASIOSampleRate sampleRate) = 0; + 52 virtual ASIOError (*getSampleRate)(ASIOSampleRate *sampleRate) = 0; + 56 virtual ASIOError (*setSampleRate)(ASIOSampleRate sampleRate) = 0; + 60 virtual ASIOError (*getClockSources)(ASIOClockSource *clocks, long *numSources) = 0; + 64 virtual ASIOError (*setClockSource)(long reference) = 0; + 68 virtual ASIOError (*getSamplePosition)(ASIOSamples *sPos, ASIOTimeStamp *tStamp) = 0; + 72 virtual ASIOError (*getChannelInfo)(ASIOChannelInfo *info) = 0; + 76 virtual ASIOError (*createBuffers)(ASIOBufferInfo *bufferInfos, long numChannels, + long bufferSize, ASIOCallbacks *callbacks) = 0; + 80 virtual ASIOError (*disposeBuffers)() = 0; + 84 virtual ASIOError (*controlPanel)() = 0; + 88 virtual ASIOError (*future)(long selector,void *opt) = 0; + 92 virtual ASIOError (*outputReady)() = 0; + }; + + The numbers in the left column show the byte offset of each function ptr + from the beginning of the vtbl. These numbers are used in the code below + to select different functions. + + In order to find the address of a particular function, theAsioDriver + must first be dereferenced to find the value of the vtbl pointer: + + mov eax, theAsioDriver + mov edx, [theAsioDriver] // edx now points to vtbl[0] + + Then an offset must be added to the vtbl pointer to select a + particular function, for example vtbl+44 points to the slot containing + a pointer to the getBufferSize function. + + Finally vtbl+x must be dereferenced to obtain the value of the function + pointer stored in that address: + + call [edx+44] // call the function pointed to by + // the value in the getBufferSize field of the vtbl + + + SEE ALSO + + Martin Fay's OpenASIO DLL at http://www.martinfay.com solves the same + problem by providing a new COM interface which wraps IASIO with an + interface that uses portable calling conventions. OpenASIO must be compiled + with MSVC, and requires that you ship the OpenASIO DLL with your + application. + + + ACKNOWLEDGEMENTS + + Ross Bencina: worked out the thiscall details above, wrote the original + Borland asm macros, and a patch for asio.cpp (which is no longer needed). + Thanks to Martin Fay for introducing me to the issues discussed here, + and to Rene G. Ceballos for assisting with asm dumps from MSVC++. + + Antti Silvast: converted the original calliasio to work with gcc and NASM + by implementing the asm code in a separate file. + + Fraser Adams: modified the original calliasio containing the Borland inline + asm to add inline asm for gcc i.e. Intel syntax for Borland and AT&T syntax + for gcc. This seems a neater approach for gcc than to have a separate .asm + file and it means that we only need one version of the thiscall patch. + + Fraser Adams: rewrote the original calliasio patch in the form of the + IASIOThiscallResolver class in order to avoid modifications to files from + the Steinberg SDK, which may have had potential licence issues. + + Andrew Baldwin: contributed fixes for compatibility problems with more + recent versions of the gcc assembler. +*/ + + +// We only need IASIOThiscallResolver at all if we are on Win32. For other +// platforms we simply bypass the IASIOThiscallResolver definition to allow us +// to be safely #include'd whatever the platform to keep client code portable +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) + + +// If microsoft compiler we can call IASIO directly so IASIOThiscallResolver +// is not used. +#if !defined(_MSC_VER) + + +#include +#include + +// We have a mechanism in iasiothiscallresolver.h to ensure that asio.h is +// #include'd before it in client code, we do NOT want to do this test here. +#define iasiothiscallresolver_sourcefile 1 +#include "iasiothiscallresolver.h" +#undef iasiothiscallresolver_sourcefile + +// iasiothiscallresolver.h redefines ASIOInit for clients, but we don't want +// this macro defined in this translation unit. +#undef ASIOInit + + +// theAsioDriver is a global pointer to the current IASIO instance which the +// ASIO SDK uses to perform all actions on the IASIO interface. We substitute +// our own forwarding interface into this pointer. +extern IASIO* theAsioDriver; + + +// The following macros define the inline assembler for BORLAND first then gcc + +#if defined(__BCPLUSPLUS__) || defined(__BORLANDC__) + + +#define CALL_THISCALL_0( resultName, thisPtr, funcOffset )\ + void *this_ = (thisPtr); \ + __asm { \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + mov resultName, eax ; \ + } + + +#define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 )\ + void *this_ = (thisPtr); \ + __asm { \ + mov eax, param1 ; \ + push eax ; \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + } + + +#define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 )\ + void *this_ = (thisPtr); \ + __asm { \ + mov eax, param1 ; \ + push eax ; \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + mov resultName, eax ; \ + } + + +#define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 )\ + void *this_ = (thisPtr); \ + void *doubleParamPtr_ (¶m1); \ + __asm { \ + mov eax, doubleParamPtr_ ; \ + push [eax+4] ; \ + push [eax] ; \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + mov resultName, eax ; \ + } + + +#define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 )\ + void *this_ = (thisPtr); \ + __asm { \ + mov eax, param2 ; \ + push eax ; \ + mov eax, param1 ; \ + push eax ; \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + mov resultName, eax ; \ + } + + +#define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\ + void *this_ = (thisPtr); \ + __asm { \ + mov eax, param4 ; \ + push eax ; \ + mov eax, param3 ; \ + push eax ; \ + mov eax, param2 ; \ + push eax ; \ + mov eax, param1 ; \ + push eax ; \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + mov resultName, eax ; \ + } + + +#elif defined(__GNUC__) + + +#define CALL_THISCALL_0( resultName, thisPtr, funcOffset ) \ + __asm__ __volatile__ ("movl (%1), %%edx\n\t" \ + "call *"#funcOffset"(%%edx)\n\t" \ + :"=a"(resultName) /* Output Operands */ \ + :"c"(thisPtr) /* Input Operands */ \ + ); \ + + +#define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 ) \ + __asm__ __volatile__ ("pushl %0\n\t" \ + "movl (%1), %%edx\n\t" \ + "call *"#funcOffset"(%%edx)\n\t" \ + : /* Output Operands */ \ + :"r"(param1), /* Input Operands */ \ + "c"(thisPtr) \ + ); \ + + +#define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 ) \ + __asm__ __volatile__ ("pushl %1\n\t" \ + "movl (%2), %%edx\n\t" \ + "call *"#funcOffset"(%%edx)\n\t" \ + :"=a"(resultName) /* Output Operands */ \ + :"r"(param1), /* Input Operands */ \ + "c"(thisPtr) \ + ); \ + + +#define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 ) \ + __asm__ __volatile__ ("pushl 4(%1)\n\t" \ + "pushl (%1)\n\t" \ + "movl (%2), %%edx\n\t" \ + "call *"#funcOffset"(%%edx);\n\t" \ + :"=a"(resultName) /* Output Operands */ \ + :"a"(¶m1), /* Input Operands */ \ + /* Note: Using "r" above instead of "a" fails */ \ + /* when using GCC 3.3.3, and maybe later versions*/\ + "c"(thisPtr) \ + ); \ + + +#define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 ) \ + __asm__ __volatile__ ("pushl %1\n\t" \ + "pushl %2\n\t" \ + "movl (%3), %%edx\n\t" \ + "call *"#funcOffset"(%%edx)\n\t" \ + :"=a"(resultName) /* Output Operands */ \ + :"r"(param2), /* Input Operands */ \ + "r"(param1), \ + "c"(thisPtr) \ + ); \ + + +#define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\ + __asm__ __volatile__ ("pushl %1\n\t" \ + "pushl %2\n\t" \ + "pushl %3\n\t" \ + "pushl %4\n\t" \ + "movl (%5), %%edx\n\t" \ + "call *"#funcOffset"(%%edx)\n\t" \ + :"=a"(resultName) /* Output Operands */ \ + :"r"(param4), /* Input Operands */ \ + "r"(param3), \ + "r"(param2), \ + "r"(param1), \ + "c"(thisPtr) \ + ); \ + +#endif + + + +// Our static singleton instance. +IASIOThiscallResolver IASIOThiscallResolver::instance; + +// Constructor called to initialize static Singleton instance above. Note that +// it is important not to clear that_ incase it has already been set by the call +// to placement new in ASIOInit(). +IASIOThiscallResolver::IASIOThiscallResolver() +{ +} + +// Constructor called from ASIOInit() below +IASIOThiscallResolver::IASIOThiscallResolver(IASIO* that) +: that_( that ) +{ +} + +// Implement IUnknown methods as assert(false). IASIOThiscallResolver is not +// really a COM object, just a wrapper which will work with the ASIO SDK. +// If you wanted to use ASIO without the SDK you might want to implement COM +// aggregation in these methods. +HRESULT STDMETHODCALLTYPE IASIOThiscallResolver::QueryInterface(REFIID riid, void **ppv) +{ + (void)riid; // suppress unused variable warning + + assert( false ); // this function should never be called by the ASIO SDK. + + *ppv = NULL; + return E_NOINTERFACE; +} + +ULONG STDMETHODCALLTYPE IASIOThiscallResolver::AddRef() +{ + assert( false ); // this function should never be called by the ASIO SDK. + + return 1; +} + +ULONG STDMETHODCALLTYPE IASIOThiscallResolver::Release() +{ + assert( false ); // this function should never be called by the ASIO SDK. + + return 1; +} + + +// Implement the IASIO interface methods by performing the vptr manipulation +// described above then delegating to the real implementation. +ASIOBool IASIOThiscallResolver::init(void *sysHandle) +{ + ASIOBool result; + CALL_THISCALL_1( result, that_, 12, sysHandle ); + return result; +} + +void IASIOThiscallResolver::getDriverName(char *name) +{ + CALL_VOID_THISCALL_1( that_, 16, name ); +} + +long IASIOThiscallResolver::getDriverVersion() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 20 ); + return result; +} + +void IASIOThiscallResolver::getErrorMessage(char *string) +{ + CALL_VOID_THISCALL_1( that_, 24, string ); +} + +ASIOError IASIOThiscallResolver::start() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 28 ); + return result; +} + +ASIOError IASIOThiscallResolver::stop() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 32 ); + return result; +} + +ASIOError IASIOThiscallResolver::getChannels(long *numInputChannels, long *numOutputChannels) +{ + ASIOBool result; + CALL_THISCALL_2( result, that_, 36, numInputChannels, numOutputChannels ); + return result; +} + +ASIOError IASIOThiscallResolver::getLatencies(long *inputLatency, long *outputLatency) +{ + ASIOBool result; + CALL_THISCALL_2( result, that_, 40, inputLatency, outputLatency ); + return result; +} + +ASIOError IASIOThiscallResolver::getBufferSize(long *minSize, long *maxSize, + long *preferredSize, long *granularity) +{ + ASIOBool result; + CALL_THISCALL_4( result, that_, 44, minSize, maxSize, preferredSize, granularity ); + return result; +} + +ASIOError IASIOThiscallResolver::canSampleRate(ASIOSampleRate sampleRate) +{ + ASIOBool result; + CALL_THISCALL_1_DOUBLE( result, that_, 48, sampleRate ); + return result; +} + +ASIOError IASIOThiscallResolver::getSampleRate(ASIOSampleRate *sampleRate) +{ + ASIOBool result; + CALL_THISCALL_1( result, that_, 52, sampleRate ); + return result; +} + +ASIOError IASIOThiscallResolver::setSampleRate(ASIOSampleRate sampleRate) +{ + ASIOBool result; + CALL_THISCALL_1_DOUBLE( result, that_, 56, sampleRate ); + return result; +} + +ASIOError IASIOThiscallResolver::getClockSources(ASIOClockSource *clocks, long *numSources) +{ + ASIOBool result; + CALL_THISCALL_2( result, that_, 60, clocks, numSources ); + return result; +} + +ASIOError IASIOThiscallResolver::setClockSource(long reference) +{ + ASIOBool result; + CALL_THISCALL_1( result, that_, 64, reference ); + return result; +} + +ASIOError IASIOThiscallResolver::getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp) +{ + ASIOBool result; + CALL_THISCALL_2( result, that_, 68, sPos, tStamp ); + return result; +} + +ASIOError IASIOThiscallResolver::getChannelInfo(ASIOChannelInfo *info) +{ + ASIOBool result; + CALL_THISCALL_1( result, that_, 72, info ); + return result; +} + +ASIOError IASIOThiscallResolver::createBuffers(ASIOBufferInfo *bufferInfos, + long numChannels, long bufferSize, ASIOCallbacks *callbacks) +{ + ASIOBool result; + CALL_THISCALL_4( result, that_, 76, bufferInfos, numChannels, bufferSize, callbacks ); + return result; +} + +ASIOError IASIOThiscallResolver::disposeBuffers() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 80 ); + return result; +} + +ASIOError IASIOThiscallResolver::controlPanel() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 84 ); + return result; +} + +ASIOError IASIOThiscallResolver::future(long selector,void *opt) +{ + ASIOBool result; + CALL_THISCALL_2( result, that_, 88, selector, opt ); + return result; +} + +ASIOError IASIOThiscallResolver::outputReady() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 92 ); + return result; +} + + +// Implement our substitute ASIOInit() method +ASIOError IASIOThiscallResolver::ASIOInit(ASIODriverInfo *info) +{ + // To ensure that our instance's vptr is correctly constructed, even if + // ASIOInit is called prior to main(), we explicitly call its constructor + // (potentially over the top of an existing instance). Note that this is + // pretty ugly, and is only safe because IASIOThiscallResolver has no + // destructor and contains no objects with destructors. + new((void*)&instance) IASIOThiscallResolver( theAsioDriver ); + + // Interpose between ASIO client code and the real driver. + theAsioDriver = &instance; + + // Note that we never need to switch theAsioDriver back to point to the + // real driver because theAsioDriver is reset to zero in ASIOExit(). + + // Delegate to the real ASIOInit + return ::ASIOInit(info); +} + + +#endif /* !defined(_MSC_VER) */ + +#endif /* Win32 */ + diff --git a/jasiohost-master/src/com/synthbot/jasiohost/iasiothiscallresolver.h b/jasiohost-master/src/com/synthbot/jasiohost/iasiothiscallresolver.h new file mode 100644 index 0000000..2919388 --- /dev/null +++ b/jasiohost-master/src/com/synthbot/jasiohost/iasiothiscallresolver.h @@ -0,0 +1,197 @@ +// **************************************************************************** +// File: IASIOThiscallResolver.h +// Description: The IASIOThiscallResolver class implements the IASIO +// interface and acts as a proxy to the real IASIO interface by +// calling through its vptr table using the thiscall calling +// convention. To put it another way, we interpose +// IASIOThiscallResolver between ASIO SDK code and the driver. +// This is necessary because most non-Microsoft compilers don't +// implement the thiscall calling convention used by IASIO. +// +// iasiothiscallresolver.cpp contains the background of this +// problem plus a technical description of the vptr +// manipulations. +// +// In order to use this mechanism one simply has to add +// iasiothiscallresolver.cpp to the list of files to compile +// and #include +// +// Note that this #include must come after the other ASIO SDK +// #includes, for example: +// +// #include +// #include +// #include +// #include +// #include +// +// Actually the important thing is to #include +// after . We have +// incorporated a test to enforce this ordering. +// +// The code transparently takes care of the interposition by +// using macro substitution to intercept calls to ASIOInit() +// and ASIOExit(). We save the original ASIO global +// "theAsioDriver" in our "that" variable, and then set +// "theAsioDriver" to equal our IASIOThiscallResolver instance. +// +// Whilst this method of resolving the thiscall problem requires +// the addition of #include to client +// code it has the advantage that it does not break the terms +// of the ASIO licence by publishing it. We are NOT modifying +// any Steinberg code here, we are merely implementing the IASIO +// interface in the same way that we would need to do if we +// wished to provide an open source ASIO driver. +// +// For compilation with MinGW -lole32 needs to be added to the +// linker options. For BORLAND, linking with Import32.lib is +// sufficient. +// +// The dependencies are with: CoInitialize, CoUninitialize, +// CoCreateInstance, CLSIDFromString - used by asiolist.cpp +// and are required on Windows whether ThiscallResolver is used +// or not. +// +// Searching for the above strings in the root library path +// of your compiler should enable the correct libraries to be +// identified if they aren't immediately obvious. +// +// Note that the current implementation of IASIOThiscallResolver +// is not COM compliant - it does not correctly implement the +// IUnknown interface. Implementing it is not necessary because +// it is not called by parts of the ASIO SDK which call through +// theAsioDriver ptr. The IUnknown methods are implemented as +// assert(false) to ensure that the code fails if they are +// ever called. +// Restrictions: None. Public Domain & Open Source distribute freely +// You may use IASIOThiscallResolver commercially as well as +// privately. +// You the user assume the responsibility for the use of the +// files, binary or text, and there is no guarantee or warranty, +// expressed or implied, including but not limited to the +// implied warranties of merchantability and fitness for a +// particular purpose. You assume all responsibility and agree +// to hold no entity, copyright holder or distributors liable +// for any loss of data or inaccurate representations of data +// as a result of using IASIOThiscallResolver. +// Version: 1.4 Added separate macro CALL_THISCALL_1_DOUBLE from +// Andrew Baldwin, and volatile for whole gcc asm blocks, +// both for compatibility with newer gcc versions. Cleaned up +// Borland asm to use one less register. +// 1.3 Switched to including assert.h for better compatibility. +// Wrapped entire .h and .cpp contents with a check for +// _MSC_VER to provide better compatibility with MS compilers. +// Changed Singleton implementation to use static instance +// instead of freestore allocated instance. Removed ASIOExit +// macro as it is no longer needed. +// 1.2 Removed semicolons from ASIOInit and ASIOExit macros to +// allow them to be embedded in expressions (if statements). +// Cleaned up some comments. Removed combase.c dependency (it +// doesn't compile with BCB anyway) by stubbing IUnknown. +// 1.1 Incorporated comments from Ross Bencina including things +// such as changing name from ThiscallResolver to +// IASIOThiscallResolver, tidying up the constructor, fixing +// a bug in IASIOThiscallResolver::ASIOExit() and improving +// portability through the use of conditional compilation +// 1.0 Initial working version. +// Created: 6/09/2003 +// Authors: Fraser Adams +// Ross Bencina +// Rene G. Ceballos +// Martin Fay +// Antti Silvast +// Andrew Baldwin +// +// **************************************************************************** + + +#ifndef included_iasiothiscallresolver_h +#define included_iasiothiscallresolver_h + +// We only need IASIOThiscallResolver at all if we are on Win32. For other +// platforms we simply bypass the IASIOThiscallResolver definition to allow us +// to be safely #include'd whatever the platform to keep client code portable +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) + + +// If microsoft compiler we can call IASIO directly so IASIOThiscallResolver +// is not used. +#if !defined(_MSC_VER) + + +// The following is in order to ensure that this header is only included after +// the other ASIO headers (except for the case of iasiothiscallresolver.cpp). +// We need to do this because IASIOThiscallResolver works by eclipsing the +// original definition of ASIOInit() with a macro (see below). +#if !defined(iasiothiscallresolver_sourcefile) + #if !defined(__ASIO_H) + #error iasiothiscallresolver.h must be included AFTER asio.h + #endif +#endif + +#include +#include /* From ASIO SDK */ + + +class IASIOThiscallResolver : public IASIO { +private: + IASIO* that_; // Points to the real IASIO + + static IASIOThiscallResolver instance; // Singleton instance + + // Constructors - declared private so construction is limited to + // our Singleton instance + IASIOThiscallResolver(); + IASIOThiscallResolver(IASIO* that); +public: + + // Methods from the IUnknown interface. We don't fully implement IUnknown + // because the ASIO SDK never calls these methods through theAsioDriver ptr. + // These methods are implemented as assert(false). + virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv); + virtual ULONG STDMETHODCALLTYPE AddRef(); + virtual ULONG STDMETHODCALLTYPE Release(); + + // Methods from the IASIO interface, implemented as forwarning calls to that. + virtual ASIOBool init(void *sysHandle); + virtual void getDriverName(char *name); + virtual long getDriverVersion(); + virtual void getErrorMessage(char *string); + virtual ASIOError start(); + virtual ASIOError stop(); + virtual ASIOError getChannels(long *numInputChannels, long *numOutputChannels); + virtual ASIOError getLatencies(long *inputLatency, long *outputLatency); + virtual ASIOError getBufferSize(long *minSize, long *maxSize, long *preferredSize, long *granularity); + virtual ASIOError canSampleRate(ASIOSampleRate sampleRate); + virtual ASIOError getSampleRate(ASIOSampleRate *sampleRate); + virtual ASIOError setSampleRate(ASIOSampleRate sampleRate); + virtual ASIOError getClockSources(ASIOClockSource *clocks, long *numSources); + virtual ASIOError setClockSource(long reference); + virtual ASIOError getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp); + virtual ASIOError getChannelInfo(ASIOChannelInfo *info); + virtual ASIOError createBuffers(ASIOBufferInfo *bufferInfos, long numChannels, long bufferSize, ASIOCallbacks *callbacks); + virtual ASIOError disposeBuffers(); + virtual ASIOError controlPanel(); + virtual ASIOError future(long selector,void *opt); + virtual ASIOError outputReady(); + + // Class method, see ASIOInit() macro below. + static ASIOError ASIOInit(ASIODriverInfo *info); // Delegates to ::ASIOInit +}; + + +// Replace calls to ASIOInit with our interposing version. +// This macro enables us to perform thiscall resolution simply by #including +// after the asio #includes (this file _must_ be +// included _after_ the asio #includes) + +#define ASIOInit(name) IASIOThiscallResolver::ASIOInit((name)) + + +#endif /* !defined(_MSC_VER) */ + +#endif /* Win32 */ + +#endif /* included_iasiothiscallresolver_h */ + + diff --git a/library/windows-amd64/jasiohost32.dll b/library/windows-amd64/jasiohost32.dll new file mode 100644 index 0000000..1c99a28 Binary files /dev/null and b/library/windows-amd64/jasiohost32.dll differ diff --git a/library/windows-amd64/jasiohost64.dll b/library/windows-amd64/jasiohost64.dll new file mode 100644 index 0000000..39e56bc Binary files /dev/null and b/library/windows-amd64/jasiohost64.dll differ diff --git a/src/processing/sound/Engine.java b/src/processing/sound/Engine.java index ce45fb0..de36598 100644 --- a/src/processing/sound/Engine.java +++ b/src/processing/sound/Engine.java @@ -38,6 +38,13 @@ class Engine { static boolean verbose = false; + /** use JavaSound where possible, PortAudio where necessary (the default) */ + static final int DRIVER_DEFAULT = 0; + /** force the JPortAudio bindings */ + static final int DRIVER_PORTAUDIO = 1; + /** force the JAsioHost ASIO bindings (Windows only) */ + static final int DRIVER_JASIO = 2; + private static AudioDeviceManager createDefaultAudioDeviceManager() { try { Class.forName("javax.sound.sampled.AudioSystem"); @@ -48,7 +55,11 @@ private static AudioDeviceManager createDefaultAudioDeviceManager() { } } - private static AudioDeviceManager createAudioDeviceManager(boolean portAudio) { + private static AudioDeviceManager createAudioDeviceManager(int driver) { + if (driver == DRIVER_JASIO) { + return Engine.createJAsioAudioDeviceManager(); + } + boolean portAudio = driver == DRIVER_PORTAUDIO; if (!portAudio) { AudioDeviceManager a = Engine.createDefaultAudioDeviceManager(); if (a.getDefaultOutputDeviceID() != -1) { @@ -103,6 +114,27 @@ public void write(int b) { } } } + /** + * Set up the JAsioHost bindings for native ASIO access. AsioDriver's static + * initializer loads the jasiohost DLL, so any problems with the native library + * (or a platform that is not Windows) show up right away as an error. + */ + private static AudioDeviceManager createJAsioAudioDeviceManager() { + if (!System.getProperty("os.name", "").toLowerCase().contains("windows")) { + throw new RuntimeException("ASIO output is only supported on Windows"); + } + try { + return new JAsioAudioDeviceManager(); + } catch (UnsatisfiedLinkError | ExceptionInInitializerError | NoClassDefFoundError e) { + if (Engine.verbose) { + e.printStackTrace(); + } + throw new RuntimeException("the JAsioHost native library (jasiohost64.dll) could not be loaded, " + + "make sure it is installed next to the Sound library's other native libraries " + + "(sound/library/windows-amd64/)"); + } + } + /** * Singleton instance that is created by the first method call to or creation * of any Sound library class. @@ -126,9 +158,17 @@ static Engine getEngine(PApplet parent) { } static Engine getEngine(PApplet parent, boolean portAudio) { + return Engine.getEngine(parent, portAudio ? Engine.DRIVER_PORTAUDIO : Engine.DRIVER_DEFAULT); + } + + static Engine getEngine(PApplet parent, int driver) { + return Engine.getEngine(parent, driver, true); + } + + static Engine getEngine(PApplet parent, int driver, boolean selectDevice) { if (Engine.singleton == null) { // this might throw a RuntimeException, which is fine - Engine.singleton = new Engine(Engine.createAudioDeviceManager(portAudio)); + Engine.singleton = new Engine(Engine.createAudioDeviceManager(driver), -1, selectDevice); } if (parent != null) { Engine.singleton.registerWithParent(parent); @@ -165,20 +205,26 @@ static AudioDeviceManager getAudioDeviceManager() { * Create a new synthesizer and connect it to the default output device. */ private Engine(AudioDeviceManager audioDeviceManager) { - this(audioDeviceManager, -1); + this(audioDeviceManager, -1, true); } private Engine(AudioDeviceManager audioDeviceManager, int outputDevice) { + this(audioDeviceManager, outputDevice, true); + } + + private Engine(AudioDeviceManager audioDeviceManager, int outputDevice, boolean selectDevice) { // suppress JSyn's INFO log messages to stop them from showing // up as redtext in the Processing console Logger logger = Logger.getLogger(com.jsyn.engine.SynthesisEngine.class.getName()); logger.setLevel(Level.WARNING); this.createSynth(audioDeviceManager); - // this method starts the synthesizer -- if the output fails, it might - // create a new PortAudio synth on the fly and try to start that - this.selectOutputDevice(outputDevice); - this.selectInputDevice(-1); + if (selectDevice) { + // this method starts the synthesizer -- if the output fails, it might + // create a new PortAudio synth on the fly and try to start that + this.selectOutputDevice(outputDevice); + this.selectInputDevice(-1); + } } private void createSynth(AudioDeviceManager deviceManager) { @@ -205,6 +251,10 @@ public boolean isUsingPortAudio() { return this.synth.getAudioDeviceManager() instanceof JPortAudioDevice; } + public boolean isUsingJAsio() { + return this.synth.getAudioDeviceManager() instanceof JAsioAudioDeviceManager; + } + /** * Switch to/from using PortAudio. * Called in two different cases: @@ -214,7 +264,8 @@ public boolean isUsingPortAudio() { */ protected boolean usePortAudio(boolean portAudio) { if (portAudio != this.isUsingPortAudio()) { - this.createSynth(Engine.createAudioDeviceManager(portAudio)); + this.createSynth(Engine.createAudioDeviceManager( + portAudio ? Engine.DRIVER_PORTAUDIO : Engine.DRIVER_DEFAULT)); // if this was called by the user (from the MultiChannel class), its their // responsibilit to select output device and start the synth! this.inputDevice = -1; @@ -222,6 +273,20 @@ protected boolean usePortAudio(boolean portAudio) { return this.isUsingPortAudio(); } + /** + * Switch to using the JAsioHost ASIO bindings. + * Called explicitly by the user through MultiChannel.useJASIO(); it's their + * responsibility to select an output device and start the synth afterwards. + */ + protected boolean useJAsio() { + if (!this.isUsingJAsio()) { + this.createSynth(Engine.createAudioDeviceManager(Engine.DRIVER_JASIO)); + this.inputDevice = -1; + this.outputDevice = -1; + } + return this.isUsingJAsio(); + } + /** * Stop the synthesizer and remove all ChannelOuts */ @@ -379,6 +444,12 @@ protected int selectOutputDevice(int deviceId) { return this.outputDevice; } + // Stop the current synthesizer before probing the new device. In + // particular, ASIO only allows one loaded driver at a time, so probing + // another driver while the current one is loaded would incorrectly + // report zero channels. + this.stopSynth(); + // if the synth is still JavaSound-based, probe the new output device early // to provoke a LineUnavailableException, in which case we should try to // switch to PortAudio. diff --git a/src/processing/sound/JAsioAudioDeviceManager.java b/src/processing/sound/JAsioAudioDeviceManager.java new file mode 100644 index 0000000..594e513 --- /dev/null +++ b/src/processing/sound/JAsioAudioDeviceManager.java @@ -0,0 +1,788 @@ +package processing.sound; + +import java.io.IOException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import com.jsyn.devices.AudioDeviceInputStream; +import com.jsyn.devices.AudioDeviceManager; +import com.jsyn.devices.AudioDeviceOutputStream; +import com.synthbot.jasiohost.AsioChannel; +import com.synthbot.jasiohost.AsioDriver; +import com.synthbot.jasiohost.AsioDriverListener; +import com.synthbot.jasiohost.AsioDriverState; +import com.synthbot.jasiohost.AsioException; + +/** + * JSyn {@link AudioDeviceManager} implementation that routes the synthesizer's + * audio output (and optionally input) through native ASIO drivers on Windows, + * using the JAsioHost library (https://github.com/mhroth/jasiohost, LGPL). + * + *

+ * Each ASIO driver registered in the system registry is exposed as one audio + * device. Since the ASIO API only allows a single driver to be loaded at any + * time, driver information that requires the driver to be loaded (such as the + * number of channels) is probed by briefly loading and unloading the driver, + * and then cached. + * + *

+ * ASIO pushes audio data to the host in bufferSwitch() callbacks, + * while JSyn's synthesis thread blocks on {@link AudioDeviceOutputStream#write} + * to pace itself. This class therefore bridges the two sides with ring buffers: + * the synthesis thread writes interleaved samples into a ring buffer which is + * drained by the ASIO callback thread. + */ +class JAsioAudioDeviceManager implements AudioDeviceManager { + + private final List driverNames; + + // deviceID -> { maxInputChannels, maxOutputChannels }, lazily probed + private final Map channelCounts = new HashMap(); + + // the (single) stream pair that's currently attached to the ASIO driver + private Session session; + + private double suggestedInputLatency = 0.010; + private double suggestedOutputLatency = 0.010; + + JAsioAudioDeviceManager() { + // this class' static initializer loads the jasiohost native library + // (and throws UnsatisfiedLinkError if it's not available) + this.driverNames = AsioDriver.getDriverNames(); + if (this.driverNames.isEmpty()) { + throw new RuntimeException("did not find any ASIO drivers registered on this system, " + + "please install the driver that came with your audio interface (or the universal " + + "ASIO4ALL driver) and try again"); + } + } + + @Override + public synchronized int getDeviceCount() { + return this.driverNames.size(); + } + + @Override + public synchronized String getDeviceName(int deviceID) { + return this.isValidDeviceId(deviceID) ? this.driverNames.get(deviceID) : ""; + } + + @Override + public String getName() { + return "JAsioHost ASIO"; + } + + private boolean isValidDeviceId(int deviceID) { + return deviceID >= 0 && deviceID < this.driverNames.size(); + } + + @Override + public synchronized int getDefaultInputDeviceID() { + for (int i = 0; i < this.driverNames.size(); i++) { + if (this.getChannelCounts(i)[0] > 0) { + return i; + } + } + return -1; + } + + @Override + public synchronized int getDefaultOutputDeviceID() { + for (int i = 0; i < this.driverNames.size(); i++) { + if (this.getChannelCounts(i)[1] > 1) { + return i; + } + } + return -1; + } + + @Override + public synchronized int getMaxInputChannels(int deviceID) { + return this.isValidDeviceId(deviceID) ? this.getChannelCounts(deviceID)[0] : 0; + } + + @Override + public synchronized int getMaxOutputChannels(int deviceID) { + return this.isValidDeviceId(deviceID) ? this.getChannelCounts(deviceID)[1] : 0; + } + + @Override + public double getDefaultLowInputLatency(int deviceID) { + return this.suggestedInputLatency; + } + + @Override + public double getDefaultHighInputLatency(int deviceID) { + return this.suggestedInputLatency; + } + + @Override + public double getDefaultLowOutputLatency(int deviceID) { + return this.suggestedOutputLatency; + } + + @Override + public double getDefaultHighOutputLatency(int deviceID) { + return this.suggestedOutputLatency; + } + + @Override + public int setSuggestedInputLatency(double latency) { + this.suggestedInputLatency = latency; + return 0; + } + + @Override + public int setSuggestedOutputLatency(double latency) { + this.suggestedOutputLatency = latency; + return 0; + } + + @Override + public synchronized AudioDeviceOutputStream createOutputStream(int deviceID, int frameRate, + int numOutputChannels) { + Session session = this.getOrCreateSession(deviceID, frameRate); + if (session.output != null) { + throw new RuntimeException("an ASIO output stream is already open on device '" + + this.getDeviceName(deviceID) + "'"); + } + session.output = new JAsioOutputStream(session, numOutputChannels); + return session.output; + } + + @Override + public synchronized AudioDeviceInputStream createInputStream(int deviceID, int frameRate, + int numInputChannels) { + Session session = this.getOrCreateSession(deviceID, frameRate); + if (session.input != null) { + throw new RuntimeException("an ASIO input stream is already open on device '" + + this.getDeviceName(deviceID) + "'"); + } + session.input = new JAsioInputStream(session, numInputChannels); + return session.input; + } + + private Session getOrCreateSession(int deviceID, int frameRate) { + if (!this.isValidDeviceId(deviceID)) { + throw new RuntimeException("not a valid ASIO device id: " + deviceID); + } + if (this.session == null) { + this.session = new Session(deviceID, frameRate); + } else if (this.session.deviceID != deviceID) { + throw new RuntimeException("the ASIO driver '" + this.session.driverName + + "' is still in use, cannot switch to '" + this.getDeviceName(deviceID) + "'"); + } + return this.session; + } + + /** + * Returns { inputChannels, outputChannels } for the given device. To query a + * driver's channel count, it has to be loaded into memory; since the ASIO API + * only permits one loaded driver at a time, we probe and unload right away, + * and cache the result for next time. If a different driver is currently in + * use by an audio session, its channel numbers are all we can report. + */ + private int[] getChannelCounts(int deviceID) { + int[] counts = this.channelCounts.get(deviceID); + if (counts == null) { + counts = this.probeChannelCounts(deviceID); + this.channelCounts.put(deviceID, counts); + } + return counts; + } + + private int[] probeChannelCounts(int deviceID) { + String driverName = this.driverNames.get(deviceID); + boolean weLoadedIt = false; + try { + if (!AsioDriver.isDriverLoaded()) { + AsioDriver.getDriver(driverName); + weLoadedIt = true; + } else if (!AsioDriver.getCurrentDriver().getName().equals(driverName)) { + // another ASIO driver is currently in use by us (or, less likely, by + // something else in this JVM): we can't load this one to probe it + return new int[] { 0, 0 }; + } + AsioDriver driver = AsioDriver.getCurrentDriver(); + return new int[] { driver.getNumChannelsInput(), driver.getNumChannelsOutput() }; + } catch (RuntimeException e) { + if (Engine.verbose) { + Engine.printWarning("failed to query the channels of ASIO driver '" + driverName + "': " + + e.getMessage()); + } + return new int[] { 0, 0 }; + } finally { + if (weLoadedIt && AsioDriver.isDriverLoaded()) { + try { + AsioDriver.getCurrentDriver().shutdownAndUnloadDriver(); + } catch (RuntimeException e) { + } + } + } + } + + /** + * Ties one ASIO driver to the input and/or output stream that JSyn's synthesis + * thread created for it, and moves the driver through its lifecycle: it is + * loaded when the stream is created, initialised and started when JSyn starts + * the stream, and fully unloaded again when the stream is stopped. + */ + private class Session implements AsioDriverListener { + + private final int deviceID; + private final String driverName; + private final int frameRate; + + private final Object lock = new Object(); + // guards the native ASIO buffers against a callback that is still in + // flight when the driver is stopped and unloaded + private final ReentrantReadWriteLock callbackLock = new ReentrantReadWriteLock(); + // guarded by lock: set to false when the streams should wind down + private volatile boolean running = false; + private boolean started = false; + + private JAsioOutputStream output; + private JAsioInputStream input; + + private AsioDriver driver; + private AsioChannel[] outputChannels; + private AsioChannel[] inputChannels; + // the number of samples per channel that ASIO hands us per callback + private int bufferSize; + + Session(int deviceID, int frameRate) { + this.deviceID = deviceID; + this.driverName = driverNames.get(deviceID); + this.frameRate = frameRate; + // load the driver eagerly (while we're still on the sketch's thread) so + // that "driver not available" errors bubble up to Engine.selectOutputDevice + // which can then fall back to the next candidate device + Engine.printMessage("loading ASIO driver '" + this.driverName + "'"); + this.driver = AsioDriver.getDriver(this.driverName); + // cache what we can see of the driver while it's loaded + channelCounts.put(deviceID, new int[] { this.driver.getNumChannelsInput(), + this.driver.getNumChannelsOutput() }); + } + + /** + * Configure, prepare and start the driver; called by the first stream that + * JSyn starts. The driver must be in the INITIALIZED state. + */ + void start() { + synchronized (this.lock) { + if (this.started) { + return; + } + this.started = true; + try { + this.doStart(); + this.running = true; + } catch (RuntimeException e) { + this.started = false; + throw new RuntimeException("failed to start ASIO driver '" + this.driverName + "': " + + e.getMessage(), e); + } + } + } + + private void doStart() { + try { + if (this.driver.canSampleRate(this.frameRate)) { + this.driver.setSampleRate(this.frameRate); + } else { + Engine.printWarning("the ASIO driver '" + this.driverName + "' does not support a " + + "sample rate of " + this.frameRate + " Hz, keeping its current rate of " + + (int) this.driver.getSampleRate() + " Hz instead"); + } + } catch (AsioException e) { + Engine.printWarning("failed to set the sample rate of ASIO driver '" + this.driverName + + " to " + this.frameRate + " Hz, keeping its current rate of " + + (int) this.driver.getSampleRate() + " Hz instead"); + } + + Set channelsToInit = new HashSet(); + int numOutputChannels = this.output != null ? this.output.channels : 0; + int numInputChannels = this.input != null ? this.input.channels : 0; + if (numOutputChannels > this.driver.getNumChannelsOutput()) { + throw new RuntimeException("the ASIO driver '" + this.driverName + "' only provides " + + this.driver.getNumChannelsOutput() + " output channels"); + } + if (numInputChannels > this.driver.getNumChannelsInput()) { + throw new RuntimeException("the ASIO driver '" + this.driverName + "' only provides " + + this.driver.getNumChannelsInput() + " input channels"); + } + this.outputChannels = new AsioChannel[numOutputChannels]; + for (int i = 0; i < numOutputChannels; i++) { + this.outputChannels[i] = this.driver.getChannelOutput(i); + channelsToInit.add(this.outputChannels[i]); + } + this.inputChannels = new AsioChannel[numInputChannels]; + for (int i = 0; i < numInputChannels; i++) { + this.inputChannels[i] = this.driver.getChannelInput(i); + channelsToInit.add(this.inputChannels[i]); + } + if (channelsToInit.isEmpty()) { + throw new RuntimeException("no channels to open on ASIO driver '" + this.driverName + "'"); + } + + this.driver.addAsioDriverListener(this); + // createBuffers() fixes the block size for the session (there is no way + // to pass a custom size through the AudioDeviceManager interface) + this.driver.createBuffers(channelsToInit); + this.bufferSize = this.driver.getBufferPreferredSize(); + + // some drivers (e.g. Realtek's) claim everything is fine but then don't + // actually allocate any buffers for the channels they report; check for + // that before starting the driver, otherwise the callbacks will just + // spam the console with NullPointerExceptions + this.checkChannelBuffers(this.outputChannels); + this.checkChannelBuffers(this.inputChannels); + + if (this.output != null) { + this.output.allocateBuffers(); + } + if (this.input != null) { + this.input.allocateBuffers(); + } + + // the driver calls back into bufferSwitch() on its own native thread + this.driver.start(); + } + + /** + * Stop the driver and unload it again; safe to call more than once. + */ + void shutdown() { + synchronized (this.lock) { + this.running = false; + this.started = false; + this.lock.notifyAll(); + } + // let any thread that's currently blocking in write()/read() wake up and + // wind down before we touch the driver + Lock writeLock = this.callbackLock.writeLock(); + writeLock.lock(); + writeLock.unlock(); + synchronized (this) { + if (this.driver != null) { + try { + this.driver.shutdownAndUnloadDriver(); + } catch (RuntimeException e) { + if (Engine.verbose) { + Engine.printWarning("error while shutting down ASIO driver '" + this.driverName + + "': " + e.getMessage()); + } + } + this.driver = null; + } + } + synchronized (JAsioAudioDeviceManager.this) { + if (JAsioAudioDeviceManager.this.session == this) { + JAsioAudioDeviceManager.this.session = null; + } + } + } + + private void checkChannelBuffers(AsioChannel[] channels) { + for (int i = 0; channels != null && i < channels.length; i++) { + if (!channels[i].isActive() || channels[i].getByteBuffer() == null) { + throw new RuntimeException("the ASIO driver '" + this.driverName + "' did not provide an " + + "audio buffer for " + channels[i] + ", it is probably not fully compatible " + + "with it - please try a different driver (e.g. the one from your audio " + + "interface's manufacturer or the universal ASIO4ALL one)"); + } + } + } + + double getLatency() { + int ringFrames = this.output != null ? this.output.ring.frames : (this.input != null + ? this.input.ring.frames : 0); + return (2.0 * this.bufferSize + ringFrames / 2.0) / this.frameRate; + } + + /* + * ASIO callbacks, called on the driver's native thread (except the requests + * which may come from a driver-internal thread as well). + */ + + @Override + public void bufferSwitch(long systemTime, long samplePosition, Set activeChannels) { + // hold the read lock for the whole callback so shutdown() can wait for + // a straggling callback before it disposes of the native buffers + Lock readLock = this.callbackLock.readLock(); + readLock.lock(); + try { + if (!this.running) { + return; + } + try { + if (this.output != null) { + this.output.fillAsioBuffers(); + } + if (this.input != null) { + this.input.drainAsioBuffers(); + } + } catch (RuntimeException e) { + // the buffers were disposed of under us while the driver was stopping + } + } finally { + readLock.unlock(); + } + } + + @Override + public void sampleRateDidChange(double sampleRate) { + Engine.printWarning("the ASIO driver '" + this.driverName + "' changed its sample rate to " + + (int) sampleRate + " Hz"); + } + + @Override + public void resetRequest() { + // can't re-initialise the driver from within a driver callback + Engine.printWarning("the ASIO driver '" + this.driverName + "' requested a reset, trying to restart it..."); + this.restart(); + } + + @Override + public void resyncRequest() { + // buffer underruns: the ring buffer is refilled with silence, nothing to do + } + + @Override + public void bufferSizeChanged(int bufferSize) { + Engine.printMessage("the ASIO driver '" + this.driverName + "' changed its preferred buffer " + + "size to " + bufferSize + ", restarting it..."); + this.restart(); + } + + @Override + public void latenciesChanged(int inputLatency, int outputLatency) { + } + + private void restart() { + new Thread(new Runnable() { + @Override + public void run() { + try { + if (!Session.this.running || Session.this.driver == null) { + return; + } + // the driver callbacks stop as soon as it leaves the RUNNING state + Session.this.driver.returnToState(AsioDriverState.INITIALIZED); + Session.this.doStart(); + } catch (RuntimeException e) { + Engine.printWarning("failed to restart the ASIO driver '" + Session.this.driverName + + "': " + e.getMessage()); + } + } + }).start(); + } + } + + /** + * JSyn-facing interleaved ring buffer that the synthesis thread blocks on + * while it is full; drained by the ASIO callback thread, one ASIO block at a + * time. + */ + private class JAsioOutputStream implements AudioDeviceOutputStream { + + private final Session session; + private final int channels; + private RingBuffer ring; + // scratch buffer to de-interleave one ASIO block into, only touched by the + // ASIO callback thread + private float[][] blocks; + + JAsioOutputStream(Session session, int channels) { + this.session = session; + this.channels = channels; + } + + void allocateBuffers() { + int ringFrames = Math.max(1024, 2 * this.session.bufferSize); + this.ring = new RingBuffer(ringFrames, this.channels); + this.blocks = new float[this.channels][this.session.bufferSize]; + } + + @Override + public void start() { + this.session.start(); + } + + @Override + public void stop() { + this.session.shutdown(); + } + + @Override + public double getLatency() { + return this.session.getLatency(); + } + + @Override + public void write(double value) throws IOException { + // extremely unlikely to be used on a multi-channel device, but keep the + // interleaved stream aligned either way + double[] single = new double[this.channels]; + single[0] = value; + this.write(single, 0, this.channels); + } + + @Override + public void write(double[] buffer) throws IOException { + this.write(buffer, 0, buffer.length); + } + + @Override + public void write(double[] buffer, int start, int count) throws IOException { + int frames = count / this.channels; + synchronized (this.session.lock) { + while (frames > 0 && this.session.running) { + try { + while (this.ring.freeFrames() == 0 && this.session.running) { + // this is what paces JSyn's synthesis thread to the ASIO clock + this.session.lock.wait(); + } + } catch (InterruptedException e) { + // JSyn is shutting down the synthesis thread + return; + } + if (!this.session.running) { + // the driver stopped under us; drop the rest instead of blocking forever + return; + } + int n = Math.min(frames, this.ring.freeFrames()); + this.ring.write(buffer, start, n); + start += n * this.channels; + frames -= n; + this.session.lock.notifyAll(); + } + } + } + + @Override + public void close() throws IOException { + } + + /** + * Called by the ASIO driver callback: hand the oldest ring buffer block(s) to + * the driver's output buffers, filling any shortfall with silence. + */ + void fillAsioBuffers() { + int blockSize = this.session.bufferSize; + synchronized (this.session.lock) { + int frames = Math.min(this.ring.usedFrames(), blockSize); + for (int c = 0; c < this.channels; c++) { + for (int i = 0; i < frames; i++) { + this.blocks[c][i] = (float) this.ring.peek(i, c); + } + for (int i = frames; i < blockSize; i++) { + this.blocks[c][i] = 0; + } + } + this.ring.discard(frames); + this.session.lock.notifyAll(); + } + for (int c = 0; c < this.channels; c++) { + this.session.outputChannels[c].write(this.blocks[c]); + } + } + } + + /** + * Fills JSyn's input side: the ASIO callback thread reads the driver's input + * buffers into an interleaved ring buffer which the synthesis thread blocks + * on while it is empty. + */ + private class JAsioInputStream implements AudioDeviceInputStream { + + private final Session session; + private final int channels; + private RingBuffer ring; + // scratch buffer to interleave one ASIO block from, only touched by the + // ASIO callback thread + private float[][] blocks; + private boolean warnedAboutOverrun = false; + + JAsioInputStream(Session session, int channels) { + this.session = session; + this.channels = channels; + } + + void allocateBuffers() { + int ringFrames = Math.max(1024, 2 * this.session.bufferSize); + this.ring = new RingBuffer(ringFrames, this.channels); + this.blocks = new float[this.channels][this.session.bufferSize]; + } + + @Override + public void start() { + this.session.start(); + } + + @Override + public void stop() { + this.session.shutdown(); + } + + @Override + public double getLatency() { + return this.session.getLatency(); + } + + /** + * Called by the ASIO driver callback: grab the newest samples from the + * driver's input buffers and push them into the ring buffer, dropping them + * if the synthesis thread is not keeping up. + */ + void drainAsioBuffers() { + for (int c = 0; c < this.channels; c++) { + this.session.inputChannels[c].read(this.blocks[c]); + } + synchronized (this.session.lock) { + if (this.ring.freeFrames() < this.session.bufferSize) { + if (!this.warnedAboutOverrun) { + Engine.printWarning("the ASIO input buffer is overrunning, audio input will " + + "contain drop-outs"); + this.warnedAboutOverrun = true; + } + return; + } + for (int i = 0; i < this.session.bufferSize; i++) { + for (int c = 0; c < this.channels; c++) { + this.ring.put(this.blocks[c][i], c); + } + } + this.session.lock.notifyAll(); + } + } + + @Override + public double read() { + double[] single = new double[this.channels]; + this.read(single, 0, this.channels); + return single[0]; + } + + @Override + public int read(double[] buffer) { + return this.read(buffer, 0, buffer.length); + } + + @Override + public int read(double[] buffer, int start, int count) { + int wantedFrames = count / this.channels; + int frames = 0; + synchronized (this.session.lock) { + try { + while (frames < wantedFrames && this.session.running) { + while (this.ring.usedFrames() == 0 && this.session.running) { + // this blocks until the ASIO callback delivers the next block + this.session.lock.wait(); + } + int n = Math.min(wantedFrames - frames, this.ring.usedFrames()); + for (int i = 0; i < n; i++) { + for (int c = 0; c < this.channels; c++) { + buffer[start++] = this.ring.peek(i, c); + } + } + frames += n; + if (n > 0) { + this.ring.discard(n); + this.session.lock.notifyAll(); + } + } + } catch (InterruptedException e) { + // JSyn is shutting down the synthesis thread + } + // JSyn de-interleaves the full requested range regardless of the + // return value, so pad whatever is left with silence + for (int i = frames; i < wantedFrames; i++) { + for (int c = 0; c < this.channels; c++) { + buffer[start++] = 0; + } + } + } + return frames * this.channels; + } + + @Override + public int available() { + synchronized (this.session.lock) { + return this.ring.usedFrames() * this.channels; + } + } + + @Override + public void close() { + } + } + + /** + * Minimal circular buffer of interleaved frames; not thread-safe on its own, + * all accesses are guarded by the session's lock. + */ + private static class RingBuffer { + + private final double[] data; + final int frames; + private final int channels; + private int readPos; + private int writePos; + private int used; + + RingBuffer(int frames, int channels) { + this.frames = frames; + this.channels = channels; + this.data = new double[frames * channels]; + } + + int usedFrames() { + return this.used; + } + + int freeFrames() { + return this.frames - this.used; + } + + /** Copy the frame at index i (from the read head) and channel c. */ + double peek(int i, int c) { + return this.data[((this.readPos + i) % this.frames) * this.channels + c]; + } + + /** Append one sample of channel c to the write head. */ + void put(double value, int c) { + this.data[this.writePos * this.channels + c] = value; + if (c == this.channels - 1) { + this.writePos = (this.writePos + 1) % this.frames; + this.used++; + } + } + + /** Append count interleaved frames from the source array. */ + void write(double[] src, int srcStart, int count) { + int srcSamples = srcStart; + for (int i = 0; i < count; i++) { + int base = this.writePos * this.channels; + int firstSample = srcSamples; + int n = Math.min(this.data.length - base, (count - i) * this.channels); + System.arraycopy(src, firstSample, this.data, base, n); + srcSamples += n; + int framesWritten = n / this.channels; + i += framesWritten - 1; + this.writePos = (this.writePos + framesWritten) % this.frames; + this.used += framesWritten; + } + } + + /** Drop count frames from the read head. */ + void discard(int count) { + this.readPos = (this.readPos + count) % this.frames; + this.used -= count; + } + } +} diff --git a/src/processing/sound/MultiChannel.java b/src/processing/sound/MultiChannel.java index 4b9713e..fa67fb2 100644 --- a/src/processing/sound/MultiChannel.java +++ b/src/processing/sound/MultiChannel.java @@ -147,4 +147,53 @@ public static boolean usePortAudio() { return engine.isUsingPortAudio(); } + /** + * Force using the native ASIO driver interface instead of JavaSound or PortAudio. + * + * While the PortAudio bindings that the Sound library falls back to do expose + * ASIO drivers on Windows, in practice they fail to open many ASIO devices. + * This method switches the library to the JAsioHost bindings which talk to the + * ASIO drivers directly, giving you the lowest possible output latency and + * reliable access to all channels of your audio interface. This is a Windows- + * only feature: on other operating systems (or if no ASIO driver is installed) + * the call prints an error and returns false. + * + * Call it at the very top of your setup(), before any other Sound + * library object is created or any other device is selected, for example: + *

+	 * MultiChannel.useJASIO();
+	 * Sound.outputDevice("ASIO4ALL v2");
+	 * 
+ * After the switch, Sound.list() lists all ASIO drivers + * registered in the system. Select the one you want to use with + * Sound.outputDevice(). Note that the ASIO API only allows one + * driver to be in use at a time. + * + * Returns true if ASIO support was successfully loaded. + * + * @webref I/O:MultiChannel + * @webBrief Force using native ASIO drivers instead of JavaSound or PortAudio. + * @see MultiChannel#usePortAudio() + * @see Sound#list() + */ + public static boolean useJASIO() { + Engine engine; + try { + // do not select an output device yet: ASIO only allows one driver to + // be loaded at a time, and Sound.list() needs to probe each driver + // to report its channel counts + engine = Engine.getEngine(null, Engine.DRIVER_JASIO, false); + } catch (RuntimeException e) { + Engine.printError(e.getMessage()); + return false; + } + try { + engine.useJAsio(); + return engine.isUsingJAsio(); + } catch (RuntimeException e) { + Engine.printError(e.getMessage()); + } + return engine.isUsingJAsio(); + } + }