Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) ASIO audio on Windows (#365)
Egor Khindikaynenb19d80e7bf06
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex df9b40f4..fa3d9410 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -102,12 +102,24 @@ Device I/O sits behind `AudioBackend` so the platform layer stays swappable:| Platform | Audio | MIDI ||---|---|---|| macOS | CoreAudio (`CoreAudioBackend.mm`) | CoreMIDI |-| Windows | WASAPI via miniaudio | WinMM via RtMidi |+| Windows | WASAPI via miniaudio, or ASIO (`audio_io/windows/`) | WinMM via RtMidi || Linux | PulseAudio / ALSA via miniaudio | ALSA via RtMidi |miniaudio runtime-links PulseAudio/ALSA with `dlopen`, so those libraries are not neededat link time.+ASIO (specs/049) is one duplex driver with one callback, while the engine opens output+(`AudioBackend`) and capture (`AudioInput`) separately. Both are thin facades+(`AsioBackend`, `AsioInput`) over one process-wide `AsioSession`, which owns the driver:+each buffer switch converts the chosen input pair, hands it to the input rings, renders,+converts the result to the chosen output pair and zeroes every other output. The session+lives in `audio_io/asio/` and builds on every platform — it reaches the driver through+`AsioDriverApi`, so `FakeAsioDriver` tests it in the smoke test; only the registry list, the+COM adapter (its own STA control thread, with timeouts) and the facades are Windows-only.+Driver resets reach the app as a polled device event and go through the normal apply path;+a driver that won't start falls back to WASAPI. Backends report device latency+(`inputLatencyFrames` / `outputLatencyFrames`), which moves recorded takes earlier.+### WarpingWarped clips are **not** stretched on the audio thread. When a clip is warped, its playeddiff --git a/BUILD.md b/BUILD.mdindex 4b53cf3b..ac6e454d 100644--- a/BUILD.md+++ b/BUILD.md@@ -190,8 +190,11 @@ a single x64 host. An ARM64 build cannot be run on x64 — the smoke test is x64### Platform details-- Audio is **WASAPI** through miniaudio (fetched by CPM); ASIO is not- supported yet.+- Audio is **WASAPI** through miniaudio, or **ASIO** (Preferences → Audio → Audio system).+ Both are fetched by CPM; the Steinberg ASIO SDK 2.3.4 is used for its headers only,+ under its GPLv3 option (`LICENSES/third-party.md`, note 8). With no audio interface at+ hand, install [FlexASIO](https://github.com/dechamps/FlexASIO) to test the ASIO path; the+ device-free part is covered by the smoke test's fake-driver self-test on every platform.- MIDI input is **WinMM** through RtMidi (fetched by CPM).- Plugin hosting is **VST3** (AU is macOS-only).- Settings, logs and projects are written to `%APPDATA%\Nota` (the counterpart ofdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2dc0a49f..3f8e356d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,15 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **ASIO on Windows**: Settings → Audio → **Audio system** now offers ASIO beside WASAPI.+ Pick the driver and the output and input channel pairs by the driver's own names (the+ other outputs stay silent); **Driver settings…** opens the driver's panel, where the buffer+ size is set, and a change there is picked up within a couple of seconds without a restart+ — playback carries on. Recording and playback share the driver's clock, so monitoring needs+ no extra buffer, and recorded takes are moved earlier by the driver's reported latency. If+ the driver is missing, busy or stops responding, Nota switches to WASAPI and the status bar+ says why; **Try again** goes back to ASIO. The Steinberg ASIO SDK is used under its GPLv3+ option (`LICENSES/third-party.md`).- **Tempo-synced scope in Nota Lens** (#119): the Scope view gains **Sync**, which lines thetrace up with the song: pick a **Span** from a quarter beat to four bars and the scope showsthat stretch of the beat grid, with beat and bar lines, a sweep line at the playhead and thediff --git a/FEATURES.md b/FEATURES.mdindex 2fe4b502..10f128bb 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -29,8 +29,8 @@ Contents- **macOS** (≥ 13.0, arm64 + x86_64): CoreAudio, CoreMIDI, **AU + VST3**hosting. Distributed as a separate `.dmg` for Apple Silicon and for Intel (ad-hoc signed).-- **Windows** (x64): WASAPI (shared + **exclusive mode** for minimum latency), WinMM- MIDI, **VST3** hosting. Distributed as an Inno Setup installer+- **Windows** (x64): WASAPI (shared + **exclusive mode** for minimum latency) or **ASIO**+ (any installed driver; falls back to WASAPI if it can't start), WinMM MIDI, **VST3** hosting. Distributed as an Inno Setup installer(`Nota-Setup-<version>-x64.exe`; arm64 is also built).- **Linux**: PulseAudio/ALSA (via miniaudio), ALSA MIDI (RtMidi), **VST3** hosting.Distributed as a portable **AppImage** (`Nota-<version>-<arch>`) that runs on any distro@@ -1226,7 +1226,12 @@ audio effects after it keep running and keep their settings; saved with the proj## Preferences- **Audio**: device, sample rate, buffer size (latency); **WASAPI exclusive mode**- (Windows).+ (Windows). On Windows, **Audio system** WASAPI / **ASIO**: the driver, the output and input+ channel pairs (by the driver's channel names; other outputs silent), **Driver settings…**+ for the driver's own panel (buffer size changes there are picked up without a restart);+ the Latency line shows the driver's latency and round trip. Recorded takes are moved+ earlier by the driver's reported latency; a missing or failed driver falls back to WASAPI+ with the reason in the status bar, and **Try again** returns to ASIO.- **MIDI**: which MIDI inputs are enabled (the house checkboxes); **MPE** on/off (on bydefault) and the per-note bend range (±12 / 24 / 48 / 96 semitones).- **Gamepads** (macOS): enable gamepad input (notes and mapped controls); the controllerdiff --git a/LICENSES/GPL-3.0-only.txt b/LICENSES/GPL-3.0-only.txtnew file mode 100644index 00000000..f288702d--- /dev/null+++ b/LICENSES/GPL-3.0-only.txt@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU General Public License is a free, copyleft license for+software and other kinds of works.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users. We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors. You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights. Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received. You must make sure that they, too, receive+or can get the source code. And you must show them these terms so they+know their rights.++ Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++ For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software. For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++ Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so. This is fundamentally incompatible with the aim of+protecting users' freedom to change the software. The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable. Therefore, we+have designed this version of the GPL to prohibit the practice for those+products. If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++ Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary. To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Use with the GNU Affero General Public License.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++ <program> Copyright (C) <year> <name of author>+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<https://www.gnu.org/licenses/>.++ The GNU General Public License does not permit incorporating your program+into proprietary programs. If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License. But first, please read+<https://www.gnu.org/licenses/why-not-lgpl.html>.diff --git a/LICENSES/README.md b/LICENSES/README.mdindex 147b83d5..07c11337 100644--- a/LICENSES/README.md+++ b/LICENSES/README.md@@ -24,6 +24,7 @@ confined to the plugin-hosting module.| File | What it is ||---|---|| [`AGPL-3.0-only.txt`](AGPL-3.0-only.txt) | Full GNU AGPLv3 text (verbatim from the FSF) |+| [`GPL-3.0-only.txt`](GPL-3.0-only.txt) | Full GNU GPLv3 text — the license the Steinberg ASIO SDK is used under (Windows builds) || [`third-party.md`](third-party.md) | Register of every dependency and its license || [`THIRD-PARTY-NOTICES.md`](THIRD-PARTY-NOTICES.md) | Copyright & attribution notices for bundled/linked third-party software |diff --git a/LICENSES/THIRD-PARTY-NOTICES.md b/LICENSES/THIRD-PARTY-NOTICES.mdindex 0458785e..3d898758 100644--- a/LICENSES/THIRD-PARTY-NOTICES.md+++ b/LICENSES/THIRD-PARTY-NOTICES.md@@ -21,6 +21,13 @@ Licensed under the **MIT License**. Bundled with JUCE for VST3 hosting. "VST" istrademark of Steinberg Media Technologies GmbH — its name and logo are governed bySteinberg's VST trademark guidelines, separate from the code license.+## Steinberg ASIO SDK+Copyright © 2025 Steinberg Media Technologies GmbH.+Used under the **GPL-3.0** option of its dual license (see [`GPL-3.0-only.txt`](GPL-3.0-only.txt)).+Interface headers for ASIO driver I/O on Windows. Source:+<https://www.steinberg.net/developers/asiosdk-open>. "ASIO" is a trademark of Steinberg+Media Technologies GmbH.+## AvaloniaCopyright © .NET Foundation and Contributors.Licensed under the **MIT License**. <https://avaloniaui.net>diff --git a/LICENSES/third-party.md b/LICENSES/third-party.mdindex 8f286970..a59b98c3 100644--- a/LICENSES/third-party.md+++ b/LICENSES/third-party.md@@ -15,6 +15,7 @@ public domain, or AGPL-compatible copyleft.| JUCE | 8.0.14 | Plugin hosting (VST3 / AU) | **AGPL-3.0** | ✅ in use — CPM release tarball — see note 1 || Steinberg VST3 SDK | bundled with JUCE 8 | VST3 hosting | MIT | ✅ in use — see note 2 || miniaudio | 0.11.25 | Audio device I/O (WASAPI / PulseAudio / ALSA) | Unlicense **or** MIT-0 | ✅ in use — CPM release tarball, fetched to build dir |+| Steinberg ASIO SDK | 2.3.4 (2025-10-15) | ASIO driver I/O (Windows) | **GPL-3.0** (dual: proprietary / GPLv3, used under GPLv3) | ✅ in use — CPM pinned zip, headers only, Windows only — see note 8 || RtMidi | 6.0.0 (byte-identical to former snapshot) | MIDI I/O (WinMM / ALSA) | MIT-like (RtMidi) | ✅ in use — CPM pinned tarball, fetched to build dir || dr_libs (dr_wav / dr_flac / dr_mp3) | headers wav 0.14.6 / flac 0.13.4 / mp3 0.7.4 (byte-identical to former snapshot) | WAV / FLAC / MP3 decoding | Unlicense **or** MIT-0 | ✅ in use — CPM pinned tarball, fetched to build dir — see note 3 || libFLAC (xiph) | 1.5.0 | FLAC encoding (export) | BSD-3-Clause | ✅ in use — CPM release tarball, fetched to build dir |@@ -86,6 +87,20 @@ the LGPL text ships in LICENSES/, the register carries this row and note, and thcombined work stays AGPL-3.0-only. No LAME symbol leaves the dylib (the `nota_*` exportlists hide it, same as JUCE in note 1).+**8 — The ASIO SDK is used under its GPLv3 option.**+Steinberg's ASIO SDK 2.3.4 is dual-licensed: the proprietary Steinberg ASIO License, or+the GNU GPL version 3 (SDK `LICENSE.txt`; steinberg.net/developers/asiosdk-open). Nota+uses it under **GPLv3**. GPLv3 §13 and AGPLv3 §13 explicitly allow combining a GPLv3+work with an AGPLv3 work: each part keeps its own license and the combined build is+conveyed under AGPLv3 terms for Nota's part, with full source — which the AGPL release+process already provides. Accepted as an *accounted* copyleft dependency+(specs/049-asio-backend). Scope: Windows builds only; only the headers `common/asio.h`,+`common/iasiodrv.h` and `common/asiosys.h` are compiled against (no SDK `.cpp`), fetched+by CPM from Steinberg's own URL pinned by SHA256. The GPLv3 text ships as+`GPL-3.0-only.txt`. **Trademark:** "ASIO" is a trademark of Steinberg Media Technologies+GmbH, governed by Steinberg's usage guidelines rather than the GPL; Nota uses the word only+as the name of the driver type (Preferences → Audio) and ships no ASIO logo.+## Not shippedJUCE is fetched at build time by CPM (into the build dir) anddiff --git a/specs/049-asio-backend/checklists/requirements.md b/specs/049-asio-backend/checklists/requirements.mdnew file mode 100644index 00000000..8e245e00--- /dev/null+++ b/specs/049-asio-backend/checklists/requirements.md@@ -0,0 +1,39 @@+# Specification Quality Checklist: ASIO audio on Windows++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-28+**Feature**: [spec.md](../spec.md)++## Content Quality++- [x] No implementation details (languages, frameworks, APIs)+- [x] Focused on user value and business needs+- [x] Written for non-technical stakeholders+- [x] All mandatory sections completed++## Requirement Completeness++- [x] No [NEEDS CLARIFICATION] markers remain+- [x] Requirements are testable and unambiguous+- [x] Success criteria are measurable+- [x] Success criteria are technology-agnostic (no implementation details)+- [x] All acceptance scenarios are defined+- [x] Edge cases are identified+- [x] Scope is clearly bounded+- [x] Dependencies and assumptions identified++## Feature Readiness++- [x] All functional requirements have clear acceptance criteria+- [x] User scenarios cover primary flows+- [x] Feature meets measurable outcomes defined in Success Criteria+- [x] No implementation details leak into specification++## Notes++- The Nota Context section and FR-005 / FR-009 name engine concepts (buffer callback,+ real-time rules) on purpose: the project template requires the context block, and the+ constitution makes audio-thread safety a requirement rather than an implementation+ choice. No code structure or API is prescribed.+- Resolved 2026-10-28: FR-004 → one stereo pair each way; FR-015 → ASIO in every+ official build, SDK under GPLv3 (see spec § Clarifications). All items pass.diff --git a/specs/049-asio-backend/contracts/c-abi.md b/specs/049-asio-backend/contracts/c-abi.mdnew file mode 100644index 00000000..0e0ce7e8--- /dev/null+++ b/specs/049-asio-backend/contracts/c-abi.md@@ -0,0 +1,54 @@+# Contract: C ABI additions (`include/nota/nota_engine.h`)++All new calls sit in the "audio device settings (M7-1)" block. Like the existing setters+they only **stage** values; `nota_audio_apply()` persists and restarts. On macOS/Linux+every ASIO call is a no-op: counts return 0, `nota_audio_asio_available()` returns 0,+setters return `NOTA_OK` and change nothing.++```c+/* Audio system (Windows): 0 = WASAPI (default), 1 = ASIO. */+NOTA_API NotaResult nota_audio_set_system(NotaEngine* engine, int32_t system);+NOTA_API int32_t nota_audio_system(const NotaEngine* engine); /* staged */+NOTA_API int32_t nota_audio_active_system(const NotaEngine* engine); /* what actually runs (after fallback) */++/* Installed ASIO drivers (refreshed by nota_audio_refresh_devices). */+NOTA_API int32_t nota_audio_asio_available(void); /* 1 if this build supports ASIO */+NOTA_API int32_t nota_audio_asio_driver_count(void);+NOTA_API const char* nota_audio_asio_driver_id(int32_t index); /* CLSID string */+NOTA_API const char* nota_audio_asio_driver_name(int32_t index); /* display name, de-duplicated */+NOTA_API NotaResult nota_audio_set_asio_driver(NotaEngine* engine, const char* id);+NOTA_API const char* nota_audio_asio_driver(const NotaEngine* engine); /* staged id */++/* Channels of the OPEN driver (0 when ASIO is not running). */+NOTA_API int32_t nota_audio_asio_channel_count(const NotaEngine* engine, int32_t is_input);+NOTA_API const char* nota_audio_asio_channel_name(const NotaEngine* engine, int32_t is_input, int32_t index);+NOTA_API NotaResult nota_audio_set_asio_pair(NotaEngine* engine, int32_t is_input, int32_t first_channel);+NOTA_API int32_t nota_audio_asio_pair(const NotaEngine* engine, int32_t is_input);++/* Open the running driver's own control panel (non-blocking for the caller). */+NOTA_API NotaResult nota_audio_asio_open_control_panel(NotaEngine* engine);++/* Device events since the last call: 0 none, 1 reset requested, 2 driver failed. Cleared on read. */+NOTA_API int32_t nota_audio_poll_device_event(NotaEngine* engine);+/* Why the last ASIO open failed — the human reason only; the app names the driver from+ * nota_audio_asio_driver + the driver list (UTF-8, engine-owned), "" if it didn't. */+NOTA_API const char* nota_audio_fallback_reason(const NotaEngine* engine);++/* Device latencies of the running backend, in frames (0 if unknown). */+NOTA_API int32_t nota_audio_input_latency_frames(const NotaEngine* engine);+NOTA_API int32_t nota_audio_output_latency_frames(const NotaEngine* engine);++/* Device-free ASIO self-test (fake driver): formats, routing, duplex, reset, fallback,+ * latency compensation. 1 = pass. Runs on every platform. */+NOTA_API int32_t nota_asio_selftest(void);+```++Errors: `nota_audio_apply` returns `NOTA_OK` when ASIO fell back to WASAPI (the app+learns it from `nota_audio_active_system` + `nota_audio_fallback_reason`), and+`NOTA_ERR_AUDIO_DEVICE` only when nothing at all could be opened — same contract as the+WASAPI exclusive fallback today.++Managed mirror: `NativeMethods.Audio.cs` (LibraryImport), `NotaEngine.Audio.cs`,+`IAudioEngine` — properties `AudioSystem`, `ActiveAudioSystem`, `AsioDrivers`,+`AsioChannels(bool input)`, `AsioPair(bool input)`, `OpenAsioControlPanel()`,+`PollDeviceEvent()`, `AudioFallbackReason`, `InputLatencyFrames`, `OutputLatencyFrames`.diff --git a/specs/049-asio-backend/contracts/preferences-ui.md b/specs/049-asio-backend/contracts/preferences-ui.mdnew file mode 100644index 00000000..c031b4cf--- /dev/null+++ b/specs/049-asio-backend/contracts/preferences-ui.md@@ -0,0 +1,28 @@+# Contract: Preferences → Audio (Windows)++Studio design language (`DESIGN.md`): existing `Row` / `Combo` / `Caption` helpers,+sentence case.++```text+Audio device+ Audio system [ WASAPI ▾ | ASIO ] ← new, Windows only+── when WASAPI ── (unchanged: Output, Input, Sample rate, Buffer size, Exclusive mode)+── when ASIO ──+ Driver [ Focusrite USB ASIO ▾ ] [ Driver settings… ]+ Output [ Output 1 + 2 ▾ ] ← pairs of the open driver+ Input [ Analog 1 + 2 ▾ ]+ Sample rate [ 48 kHz ▾ ] ← request; refusal reverts + caption+ Buffer size 256 frames (set in the driver's settings) ← read-only text+ Latency 5.3 ms · 256 frames @ 48 kHz · round trip 11.2 ms+```++- No ASIO driver installed: the ASIO option is disabled with the caption "No ASIO driver+ found. Install your interface's driver, or a generic one such as FlexASIO." WASAPI+ stays selected.+- Fallback active: the Latency line reads "ASIO unavailable (<reason>) → WASAPI"; the+ status bar shows "ASIO driver ‘<name>’ couldn't start — using WASAPI. <reason>".+- Changing Audio system, Driver, Output or Input calls the existing `Apply()`.+- "Driver settings…" is enabled only while ASIO is running.+- Device event polling (in `MainWindowViewModel`'s tick): `RESET_REQUESTED` → apply,+ resume playback if it was playing, status "Audio: driver settings changed · 128 frames";+ `DRIVER_FAILED` → apply (falls back), status as above.diff --git a/specs/049-asio-backend/data-model.md b/specs/049-asio-backend/data-model.mdnew file mode 100644index 00000000..13f9bd25--- /dev/null+++ b/specs/049-asio-backend/data-model.md@@ -0,0 +1,64 @@+# Data model: ASIO audio on Windows++Engine-side state; nothing here is stored in the project file.++## AudioConfig (extended, `src/audio_io/AudioConfig.h`, persisted in `audio.json`)++| Field | Type | Default | Notes |+|---|---|---|---|+| outputDeviceUid, inputDeviceUid, sampleRate, bufferFrames, wasapiExclusive | — | — | unchanged |+| `audioSystem` | enum `AudioSystem { Wasapi, Asio }` | `Wasapi` | Windows only; read as `Wasapi` elsewhere |+| `asioDriverClsid` | string | `""` | primary key of the chosen driver |+| `asioDriverName` | string | `""` | fallback key if the CLSID is gone |+| `asioOutputPair` | int32 | 0 | first channel index of the master pair; even numbers in UI |+| `asioInputPair` | int32 | 0 | first channel index of the recording pair |++Validation: an out-of-range pair is clamped to 0 at open; an unknown driver → fallback+(FR-011). `bufferFrames` is ignored while `audioSystem == Asio` (driver decides, FR-008);+`sampleRate` is requested via `setSampleRate` if non-zero and supported.++## AsioDriverInfo (enumeration result, not persisted)++`clsid`, `name` (registry key), `displayName` (name + ` (2)` suffix for duplicates).++## AsioChannelInfo (per open driver)++`index`, `isInput`, `name` (from `getChannelInfo`), `sampleType` (ASIO enum).+Pairs shown to the user are derived: `(i, i+1)` for even `i`; a trailing odd channel is a+mono "pair".++## AsioSession state machine++```text+Closed ──load(clsid)──▶ Loaded ──init()+createBuffers()──▶ Prepared ──start()──▶ Running+ ▲ │ fail │ fail │+ │ ▼ ▼ │+ └────────────── Failed(reason) ◀───────────────────────────┴──── watchdog / error ┘+Running ──resetRequested──▶ (event to app) ──apply──▶ Closed ──▶ … ──▶ Running+```++- `Failed(reason)`: reason is one of `NotInstalled`, `LoadFailed`, `InitFailed`+ (driver returned false / busy), `UnsupportedFormat(type)`, `NoOutputs`,+ `Timeout`, `Stopped` (no buffer callback for 2 s while running). The engine then starts+ the miniaudio WASAPI backend with system defaults and keeps `audioSystem = Asio` in the+ saved config (FR-011).+- Atomics set from `asioMessage` / `bufferSwitch`: `resetRequested`, `lastCallbackTick`.+ Overloads call the engine's xrun counter directly (an atomic increment). The watchdog+ runs inside `nota_audio_poll_device_event` (UI tick, ≈ 33 ms) rather than on its own+ thread: a running driver silent for 2 s moves to `Failed(Stopped)` on the next poll.+ The restart that `DRIVER_FAILED` triggers runs WASAPI straight away (a driver that starts+ but stays silent would otherwise fail forever); the user's next apply tries ASIO again.+ Events are deferred while the driver's own panel is open.+- A driver call that times out abandons the driver: its callbacks are cut off and no other+ ASIO driver opens until Nota restarts (ASIO callbacks can't tell two drivers apart).+- A sample rate the driver refuses is dropped from the saved config (back to device default).++## Device event (C ABI poll)++`NotaAudioDeviceEvent { NONE = 0, RESET_REQUESTED = 1, DRIVER_FAILED = 2 }` — returned by+`nota_audio_poll_device_event`, cleared on read.++## Latency++`AudioBackend::inputLatencyFrames()`, `outputLatencyFrames()` (default 0). Recording+offset = input + output; the Latency line shows output (and round trip when recording).diff --git a/specs/049-asio-backend/plan.md b/specs/049-asio-backend/plan.mdnew file mode 100644index 00000000..d1372aa0--- /dev/null+++ b/specs/049-asio-backend/plan.md@@ -0,0 +1,167 @@+# Implementation Plan: ASIO audio on Windows++**Branch**: `049-asio-backend` | **Date**: 2026-10-28 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `specs/049-asio-backend/spec.md`++## Summary++Add ASIO as a second audio system on Windows beside WASAPI. One `AsioSession` owns the+single open ASIO driver (loaded through its COM interface, enumerated from the registry)+and backs both engine-facing interfaces: `AsioBackend : AudioBackend` for output and+`AsioInput : AudioInput` for capture. Each driver buffer is converted from the driver's+format, given to the existing input rings, rendered, and converted back, on the driver's+thread. Driver resets reach the app as a polled device event and go through the existing+apply path. Any failure falls back to the miniaudio WASAPI backend. The Steinberg ASIO SDK+2.3.4 is fetched by CPM and used under its GPLv3 option, recorded in the license register.+Details: [research.md](research.md).++## Nota: Read Before Planning++Consult the matching source of truth before designing:++- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): the AR rules table is binding (AR-4 lock-free queue, AR-5 immutable snapshots, AR-6 audio-thread restrictions, AR-7 pure C ABI, AR-9 `Transport` is the only source of musical time).+- **UI work** → [`DESIGN.md`](../../DESIGN.md) (Studio design language) and the `nota-design` skill.+- **Build / packaging** → [`BUILD.md`](../../BUILD.md).+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md): licensing, dependency policy, PR expectations.++## Technical Context++**Language/Version**: C++20 (engine, MSVC on Windows; the platform-independent pieces also build with clang on macOS/Linux), C# / .NET 10 (managed app)++**Primary Dependencies**: **NEW** — Steinberg ASIO SDK 2.3.4 (headers only: `asio.h`, `iasiodrv.h`, `asiosys.h`), GPLv3 option, CPM pinned URL + SHA256, Windows targets only (R1). Existing: miniaudio (WASAPI fallback), nlohmann/json (`audio.json`), Avalonia.++**Storage**: `audio.json` in `%APPDATA%\Nota` gains five keys (data-model.md); no project-file change.++**Audio-Thread Impact**: The ASIO `bufferSwitch` becomes the audio thread on Windows when ASIO is selected. It only converts samples, pushes input frames into the existing lock-free rings (AR-4) and calls the existing render callback — no allocation, locks or I/O (AR-6). All buffers are sized at `createBuffers` on the driver control thread. Driver load/init/reset/control panel run on a dedicated non-real-time thread (R4). `asioMessage` only sets atomics.++**Testing**: `tests/Nota.SmokeTest` calls a new device-free `nota_asio_selftest()` (fake driver, every platform); manual checks on Windows hardware ([quickstart.md](quickstart.md)).++**Target Platform**: Windows 10+ x64 and ARM64 (ASIO); macOS and Linux unchanged (ASIO calls are no-ops).++**Project Type**: desktop app — native engine + managed UI.++**Performance Goals**: 0 xruns for 10 min at 64 frames / 48 kHz on a 16-track project (SC-001); per-buffer conversion cost negligible next to render (O(frames × chosen channels) plus zeroing other outputs).++**Constraints**: one ASIO driver per process; no launch hang > 5 s on a broken driver (control-thread timeouts); reset → audio ≤ 2 s; stereo engine (one pair each way).++**Scale/Scope**: ~10 new engine files (≈ 1.2 k lines), ~15 new C ABI calls, one Preferences section, one license row.++## Constitution Check++*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*++| Principle | Status | How |+|---|---|---|+| I. Real-time audio safety | ✅ | `bufferSwitch` converts + calls the existing render/input callbacks only; reset/restart off the audio thread; atomics from `asioMessage` (R4, R5) |+| II. Boundary discipline | ✅ | All new surface is plain C in `nota_engine.h` (contracts/c-abi.md); no JUCE — the core engine's own ASIO code, not JUCE's |+| III. Licensing hygiene | ✅ with a recorded decision | New copyleft dependency (ASIO SDK, GPLv3). Compatible with AGPL-3.0-only via GPLv3 §13 / AGPLv3 §13; register row + note + notice + PR rationale (R1). New files carry the SPDX header. See Complexity Tracking |+| IV. Verification gate | ✅ | `nota_asio_selftest` in the smoke test on every platform; `build-win.ps1` compiles the ASIO path |+| V. One logical change per PR | ✅ | One feature; engine, ABI, UI, docs land together (they're unusable apart). Recording latency compensation is generic but only switched on by ASIO |+| VI. Docs in sync | ✅ | CHANGELOG, FEATURES.md (nota-features), user manual EN+RU (nota-docs), BUILD.md, ARCHITECTURE.md table |+| VII. Spec-first | ✅ | spec → clarifications → this plan |+| VIII. Rules not bent | ✅ | No rule is weakened; the dependency goes through the documented policy |++**Post-design re-check (after Phase 1)**: unchanged — the design adds no audio-thread+work beyond conversion, no ABI escape hatches, and the single new dependency is headers+only.++## Project Structure++### Documentation (this feature)++```text+specs/049-asio-backend/+├── spec.md+├── plan.md # this file+├── research.md # R1–R11 decisions+├── data-model.md # AudioConfig fields, session state machine, device events+├── quickstart.md # automated + manual validation+├── contracts/+│ ├── c-abi.md # new nota_audio_* calls+│ └── preferences-ui.md+├── checklists/requirements.md+└── tasks.md # /speckit-tasks+```++### Source Code (repository root)++```text+src/native/nota.engine/+├── cmake/dependencies.cmake # + CPMAddPackage(asiosdk …) under WIN32, DOWNLOAD_ONLY+├── CMakeLists.txt # + windows/ ASIO sources on WIN32; asio_common sources everywhere+├── include/nota/nota_engine.h # + calls in contracts/c-abi.md+└── src/+ ├── abi/nota_engine_audio.cpp # C ABI glue, beside the M7-1 calls+ ├── audio_io/+ │ ├── AudioBackend.h # + input/outputLatencyFrames(), sharesInputClock()+ │ ├── AudioConfig.h # + audioSystem, asioDriverClsid/Name, asioOutputPair/InputPair+ │ ├── AudioBackendFactory.{h,cpp} # choose miniaudio vs ASIO pair by audioSystem; shared session+ │ ├── ConfigJson.cpp # read/write the new audio.json keys+ │ ├── asio/ # platform-independent, built everywhere (self-test)+ │ │ ├── AsioSampleFormat.{h,cpp} # Int16/24/32(+LSB16..24)/Float32/64 LSB ⇄ float; MSB/DSD refused+ │ │ ├── AsioDriverApi.h # the IASIO subset AsioSession uses+ │ │ ├── AsioSession.{h,cpp} # state machine, buffer switch, pair routing, silence, watchdog, events+ │ │ └── FakeAsioDriver.{h,cpp} # test driver for nota_asio_selftest+ │ └── windows/ # WIN32 only+ │ ├── AsioDriverList.{h,cpp} # registry enumeration (HKLM\SOFTWARE\ASIO), de-duplicated names+ │ ├── ComAsioDriver.{h,cpp} # IASIO adapter + STA control thread + timeouts+ │ ├── AsioBackend.{h,cpp} # AudioBackend facade over AsioSession+ │ └── AsioInput.{h,cpp} # AudioInput facade over AsioSession+ └── engine/+ ├── Engine.cpp # fallback to WASAPI on ASIO failure; device-event + reason accessors+ └── Engine_Recording.cpp # latency-compensated take start; no monitor cushion when sharesInputClock()++src/managed/+├── Nota.Infrastructure/Interop/NativeMethods.Audio.cs, NotaEngine.Audio.cs # mirror the ABI+├── Nota.Application/Engine/IAudioEngine.cs # new members+├── Nota.Presentation/ViewModels/MainWindowViewModel.cs # poll device events in the tick; fallback status+└── Nota.App/PreferencesWindow.cs # Audio system row + ASIO rows (contracts/preferences-ui.md)++tests/Nota.SmokeTest/Program.cs # Check(NotaEngine.AsioSelfTest(), …); ABI no-op checks off Windows++LICENSES/third-party.md, LICENSES/THIRD-PARTY-NOTICES.md # ASIO SDK row + note 8 (GPLv3 compatibility, trademark)+BUILD.md, ARCHITECTURE.md, CHANGELOG.md, FEATURES.md # docs; user manual via nota-docs+```++**Structure Decision**: ASIO code lives beside the other device backends in+`src/audio_io/`, split so that everything not needing COM (`asio/`) builds on all+platforms for the self-test, and only the registry/COM/facade layer (`windows/`) is+Windows-only. The engine keeps its two interfaces; only the factory knows a session is+shared.++## Implementation order (for /speckit-tasks)++1. **Dependency & build**: CPM block for the SDK (WIN32), include path for `asio/` on all+ platforms (only our headers there; the SDK enum values `AsioSampleFormat` needs are+ mirrored as our own constants so non-Windows builds don't fetch the SDK). License row,+ note, notice.+2. **Pure core** (`asio/`): sample formats, `AsioDriverApi`, `AsioSession`,+ `FakeAsioDriver`, `nota_asio_selftest` + smoke check. — testable on macOS.+3. **Engine hooks**: `AudioBackend` latency/clock virtuals, recording compensation,+ monitor cushion, `AudioConfig` + JSON keys, factory selection, fallback to WASAPI,+ device-event + reason accessors, C ABI.+4. **Windows layer**: driver list, COM adapter + control thread, facades. Build on+ Windows (`build-win.ps1`).+5. **Managed + UI**: interop, `IAudioEngine`, Preferences rows, device-event polling,+ status texts.+6. **Docs**: BUILD.md (remove "ASIO is not supported yet"), ARCHITECTURE.md platform+ table, CHANGELOG, FEATURES.md, user manual (EN+RU).+7. **Manual validation** on Windows per quickstart.md.++## Risks++- **No Windows hardware in the loop here**: the COM/driver layer can only be compiled in+ CI and tested by hand. Mitigation: keep `windows/` thin; everything stateful lives in+ the fake-testable `AsioSession`.+- **Misbehaving drivers** (hang in `init`, call `bufferSwitch` after `stop`, change+ buffer size without a reset message): control-thread timeouts, an `active_` atomic+ checked at the top of `bufferSwitch`, and a buffer-size check each switch that turns a+ silent change into a reset request.+- **ARM64**: few native ARM64 ASIO drivers exist; the UI explains an empty list.++## Complexity Tracking++| Violation | Why Needed | Simpler Alternative Rejected Because |+|-----------|------------|-------------------------------------|+| New copyleft dependency (ASIO SDK, GPLv3) — CONTRIBUTING.md rejects copyleft deps "not already accounted for" | ASIO is impossible without the SDK's interface definitions; it is the feature | Proprietary SDK license can't be combined with AGPL distribution; an opt-in build was rejected by the user (spec § Clarifications Q2). GPLv3 is AGPL-compatible (§13), so the decision is recorded rather than the rule bent |diff --git a/specs/049-asio-backend/quickstart.md b/specs/049-asio-backend/quickstart.mdnew file mode 100644index 00000000..1f33a473--- /dev/null+++ b/specs/049-asio-backend/quickstart.md@@ -0,0 +1,37 @@+# Quickstart: validating ASIO on Windows++## Automated (every platform, CI included)++```bash+scripts/build.sh # macOS; Linux: scripts/build-linux.sh+```++```powershell+pwsh scripts/build-win.ps1 # Windows x64: also proves the SDK fetch + ASIO TU compile+```++Expected: smoke test green, including the line+`ASIO self-test (fake driver): formats, pair routing, duplex, reset, fallback, latency`.+No ASIO driver is needed. See [contracts/c-abi.md](contracts/c-abi.md) for what+`nota_asio_selftest` covers.++## Manual (Windows machine)++Prerequisites: a hardware interface with its ASIO driver, **or** FlexASIO+(github.com/dechamps/FlexASIO) installed; a loopback cable (out 1/2 → in 1/2) for the+recording check.++| # | Step | Expected |+|---|---|---|+| 1 | Preferences → Audio → Audio system = ASIO, pick the driver | Driver, Output, Input rows appear; Latency shows the driver's buffer and rate (US1) |+| 2 | Play test tone | Heard on the chosen output pair only; other outputs silent (FR-006) |+| 3 | Quit, relaunch | ASIO + same driver + same pairs reopen (US1-3) |+| 4 | Driver settings… → change buffer while playing | Playback resumes ≤ 2 s; Latency updates (US3, SC-004) — repeat 10× |+| 5 | Sample rate row → a rate the driver lacks | Row reverts, caption explains (US3-3) |+| 6 | Arm an audio track, record a click through the loopback for 10 min | Recorded clicks align with the source within 1 sample (SC-006) |+| 7 | Quit, unplug the interface (or open the driver in another DAW), launch | Starts on WASAPI ≤ 5 s, status names the driver and reason; Preferences still shows ASIO (US4, SC-005) |+| 8 | Unplug while playing | Falls back to WASAPI ≤ 3 s, transport position kept (US4-2) |+| 9 | Switch back to WASAPI | Another app can now open the ASIO driver (FR-012) |+| 10 | 16-track project, 64 frames @ 48 kHz, 10 min | 0 xruns on the reference machine (SC-001) |++Without a Windows machine, steps 1–10 are pending; record that in the PR.diff --git a/specs/049-asio-backend/research.md b/specs/049-asio-backend/research.mdnew file mode 100644index 00000000..bc808448--- /dev/null+++ b/specs/049-asio-backend/research.md@@ -0,0 +1,186 @@+# Research: ASIO audio on Windows++Phase 0 for [plan.md](plan.md). Each item: decision, rationale, alternatives.++## R1 — License of the ASIO SDK++**Decision**: Use the Steinberg ASIO SDK **2.3.4** under its **GPLv3** option, fetched by+CPM from the pinned URL+`https://download.steinberg.net/sdk_downloads/ASIO-SDK_2.3.4_2025-10-15.zip` (≈ 8.9 MB)+with a `URL_HASH SHA256=…` computed when the task lands. Record it in+`LICENSES/third-party.md` as a new row with a note, plus `THIRD-PARTY-NOTICES.md`.++**Rationale**: Verified 2026-10-28 at the source:+- The SDK's `LICENSE.txt` says it is licensed "under the terms of the Steinberg ASIO+ License, or alternatively under the terms of the General Public License (GPL) Version 3";+ `changes.txt` for 2.3.4: "new DUAL licensing: Proprietary and GPVv3".+- steinberg.net/developers/asiosdk-open: "Steinberg ASIO technology is available in open+ source form under a GNU General Public License, version GPLv3." The name and logo stay+ trademarks; using them is optional and governed by Steinberg's usage guidelines, not the+ GPL.+- GPLv3 §13 and AGPLv3 §13 explicitly allow combining a GPLv3 work with an AGPLv3 work;+ each part keeps its own license and the combined binary is conveyed under AGPLv3 terms+ for Nota's part. Nota is already AGPL-3.0-only and ships full source, so the GPLv3+ source-availability duty is met by the existing release process.+- CONTRIBUTING.md rejects copyleft dependencies "not already accounted for"; this plan+ accounts for it explicitly (register row + note + PR rationale), which is the+ deliberate decision the policy asks for.++**Trademark handling**: UI text says "ASIO" only as the name of the driver type (a+permitted product-related context). No ASIO logo is shipped. "Nota" names nothing+"ASIO…".++**Fetch rather than vendor**: consistent with every other dependency (spec 032 removed+vendored trees). Only `common/asio.h`, `common/iasiodrv.h`, `common/asiosys.h` are+compiled against; no SDK `.cpp` is built (see R3).++**Alternatives**: proprietary license (incompatible with AGPL distribution — rejected);+the unofficial GitHub mirror `audiosdk/asio` (not Steinberg's; rejected in favour of the+official URL); opt-in build flag (rejected by the user in spec § Clarifications).++## R2 — Where the ASIO code lives and how it plugs into the engine++**Decision**: A new `src/native/nota.engine/src/audio_io/windows/` folder with one+**`AsioSession`** object that owns the single open driver, and two thin facades over it:+`AsioBackend : AudioBackend` (output) and `AsioInput : AudioInput` (capture).+`AudioBackendFactory` picks the miniaudio or ASIO pair from `AudioConfig::audioSystem`.++**Rationale**: `AudioBackend` and `AudioInput` are separate objects today, opened by+`Engine::start()` and `Engine::ensureAudioInput()` respectively. ASIO is one duplex+driver with one callback. Keeping both interfaces and backing them with one session+means `Engine`, `Engine_Recording.cpp` (input rings, monitor cushion, record tap) and the+C ABI device flow keep their shape. In `bufferSwitch` the session converts the chosen+input pair to interleaved stereo float and hands it to the registered `InputCallback`+**before** calling the `RenderCallback`, then converts the rendered stereo to the chosen+output pair.++**Alternatives**: a new duplex `AudioDevice` interface replacing both (cleaner long-term,+but touches macOS/Linux paths for no user benefit — rejected for this feature); JUCE's+`AudioIODeviceType::createAudioIODeviceType_ASIO` (violates AR "JUCE only in+pluginhost/" — rejected); RtAudio/PortAudio (a second device library beside miniaudio for+a thin wrapper — rejected).++## R3 — Talking to drivers: SDK host code vs. the COM interface++**Decision**: Compile only the SDK **headers**. Enumerate drivers ourselves from the+registry (`HKEY_LOCAL_MACHINE\SOFTWARE\ASIO\<name>` → `CLSID`, `Description`), create the+driver with `CoCreateInstance(clsid, …, IID = clsid)` and call it through `IASIO`+(`iasiodrv.h`). Do not build `host/asiodrivers.cpp`, `host/pc/asiolist.cpp` or+`common/asio.cpp`.++**Rationale**: the SDK host files keep global singletons (`theAsioDriver`,+`asioDrivers`), use ANSI APIs, and leak on some paths; the COM interface is ~20 methods+and lets `AsioSession` hold the driver pointer itself. Registry enumeration is ~60+lines. 32-bit drivers live under `WOW6432Node` and are skipped by the 64-bit build by+construction (spec edge case). On ARM64 only native ARM64 drivers register in the ARM64+view.++**Alternatives**: SDK host helpers (global state, ANSI) — rejected.++## R4 — Threads++**Decision**:+- **Driver thread** (`AsioSession` control thread): a dedicated thread initialised with+ `CoInitializeEx(COINIT_APARTMENTTHREADED)` that creates, inits, starts, stops, disposes+ the driver and opens `controlPanel()`. Engine calls are marshalled to it and waited on+ with a timeout (SC-005: no launch hangs > 5 s; a timed-out driver is abandoned and the+ WASAPI fallback taken).+- **Buffer thread**: the driver's own thread calling `bufferSwitch` /+ `bufferSwitchTimeInfo`. It is the engine's audio thread: convert, call the input+ callback, render, convert. No allocation, no locks, no I/O (AR-6). On first entry it+ joins MMCSS "Pro Audio" only if the driver did not already (ASIO SDK 2.3 §MMCSS).+- **asioMessage** may arrive on any thread: it only sets atomics (`resetRequested_`,+ `latencyChanged_`, `resync_`) and returns.++**Rationale**: many drivers require that all non-callback calls come from the thread that+created them, and that it pumps messages for the control panel. ASIO callbacks carry no+user-data pointer, so a single static `AsioSession* g_active` routes them — acceptable+because ASIO allows one driver per process anyway.++## R5 — Reset requests, sample-rate changes and the app++**Decision**: `kAsioResetRequest`, `kAsioBufferSizeChange`, `kAsioLatenciesChanged` and+`sampleRateDidChange` set `resetRequested_`. The engine exposes it through the C ABI+(`nota_audio_poll_device_event`); `MainWindowViewModel`'s existing UI tick polls it and+runs the normal apply path, then resumes playback if it was playing. The driver is never+restarted from inside a driver callback.++**Rationale**: re-uses `ApplyAudioSettings()` (stops the playhead clock, restarts the+backend, re-prepares nodes, re-computes PDC) — the one tested restart path. Polled at UI+tick rate (≈ 16–33 ms), so the 2-second budget (FR-009) is dominated by the driver's own+re-init.++**Alternatives**: restart from the driver control thread directly (races the UI thread's+engine calls — rejected).++## R6 — Sample formats++**Decision**: Support `ASIOSTInt16LSB`, `ASIOSTInt24LSB` (packed 3-byte),+`ASIOSTInt32LSB`, `ASIOSTInt32LSB16/18/20/24` (left-justified variants), `ASIOSTFloat32LSB`,+`ASIOSTFloat64LSB`. Refuse every MSB and DSD type with a named error (spec edge case).+Integer → float scales by `1/2^(bits-1)`; float → integer clamps to [-1, 1) and rounds,+no dither (the master is already float and dither is an export concern).++**Rationale**: these cover every Windows driver in practice; Int32LSB and Float32LSB are+the common ones. Conversions are pure functions in `AsioSampleFormat.{h,cpp}`,+platform-independent, so the smoke test exercises them on macOS and Linux too.++## R7 — Latency reporting and recording compensation++**Finding**: the engine has **no hardware-latency compensation for recording today** on+any platform (plugin delay compensation exists; device latency does not).++**Decision**: add `virtual int32_t inputLatencyFrames() const { return 0; }` and+`outputLatencyFrames()` to `AudioBackend`; `AsioBackend` returns `ASIOGetLatencies`+values. When a hardware-input take is materialised, the engine shifts the clip start+earlier by `input + output` latency frames. Backends returning 0 (CoreAudio, miniaudio)+behave exactly as today. The Latency line shows output latency (and round trip when an+input is in use).++**Rationale**: FR-010 / SC-006 need it; making it backend-generic keeps one code path and+leaves room for CoreAudio to report its latencies later (out of scope here).++## R8 — Monitoring cushion in duplex mode++**Decision**: when input and output share a clock (ASIO), `pullMonitorInput` uses no+cushion: input for block *n* is pushed in the same callback before block *n* renders, so+the queue always holds exactly the current block. A backend flag+`sharesInputClock()` (default false) selects it.++**Rationale**: the current one-block cushion exists because WASAPI/CoreAudio capture and+playback run on separate clocks. Keeping it under ASIO would add a full buffer of+monitoring latency for nothing.++## R9 — Channel pair selection++**Decision** (spec Q1 → A): `AudioConfig` gains `asioOutputPair` and `asioInputPair` —+the index of the first channel of the pair (0, 2, 4, …). The UI lists pairs by the+driver's channel names ("Out 1/2", "Analog 3/4"). A pair whose second channel doesn't+exist is mono (spec edge case: down-sum on output, duplicate on input). All other+outputs get zeros every buffer (FR-006): output buffers are cleared once at+`createBuffers` and the session writes only the chosen pair, plus re-zeroes all others+each switch (drivers may not preserve buffer contents).++## R10 — Persistence and migration++**Decision**: `audio.json` (existing, nlohmann/json, atomic write) gains+`"audioSystem": "wasapi" | "asio"`, `"asioDriver": "<CLSID string>"`,+`"asioDriverName": "<name>"`, `"asioOutputPair": 0`, `"asioInputPair": 0`. Missing keys+mean today's behaviour (WASAPI). The driver is matched by CLSID first, then by name+(drivers reinstalled with a new CLSID), with duplicate names disambiguated by a+` (2)` suffix in display only.++## R11 — Testing without a driver++**Decision**: `AsioSession` talks to drivers through a small internal interface+`AsioDriverApi` (the subset of `IASIO` used). On Windows `ComAsioDriver` adapts `IASIO`;+everywhere, `FakeAsioDriver` (test-only, compiled into the engine like other self-tests)+simulates a driver with configurable formats, channel counts, latencies, a reset request+and a "stops calling back" failure, and drives `bufferSwitch` from a test thread.+New self-test `nota_asio_selftest()` covers format conversion, pair routing and silence,+duplex ordering, reset → event, failure → fallback flag and latency compensation. The+smoke test calls it on every platform. Windows CI has no ASIO driver, so the real-driver+path is verified by hand (quickstart.md).++**Rationale**: FR-016; matches the project's existing `*SelfTest()` pattern+(`XrunSelfTest`, `AudioRecordSelfTest`).diff --git a/specs/049-asio-backend/spec.md b/specs/049-asio-backend/spec.mdnew file mode 100644index 00000000..2fed1beb--- /dev/null+++ b/specs/049-asio-backend/spec.md@@ -0,0 +1,303 @@+# Feature Specification: ASIO audio on Windows++**Feature Branch**: `049-asio-backend`++**Created**: 2026-10-28++**Status**: Draft++**Input**: User description: "ASIO audio backend on Windows: add a native ASIO driver backend behind the engine's AudioBackend interface (alongside the existing miniaudio WASAPI backend, which stays as the fallback), so users with audio interfaces that ship ASIO drivers (or FlexASIO/ASIO4ALL) get low, stable latency. Includes: choosing the ASIO driver in Preferences → Audio, opening the driver's control panel, handling driver reset requests (buffer size / sample rate changed in the driver panel), sample-format conversion (Int16/Int24/Int32/Float32 LSB), duplex input+output on one driver, and graceful fallback to WASAPI if the driver fails to load. Licensing: Steinberg ASIO SDK is dual-licensed proprietary/GPLv3; GPLv3 is AGPLv3-compatible but needs the deliberate dependency decision required by CONTRIBUTING.md (third-party.md row + rationale)."++## Nota Context *(fill in — drives plan and tasks)*++**Feature area** *(pick the main one)*:++- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [x] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),+[`FEATURES.md`](../../FEATURES.md).++Today Windows audio goes only through WASAPI (shared, or exclusive via a Preferences+switch), via miniaudio — `src/native/nota.engine/src/audio_io/desktop/MiniaudioBackend.*`+for output and `MiniaudioInput.*` for capture, chosen in `AudioBackendFactory.cpp`.+Output and input are **separate** objects (`AudioBackend`, `AudioInput`) that open+separate devices and hand the engine interleaved **stereo** float. ASIO is the opposite+shape: one driver per process, input and output on the same driver and the same clock,+one buffer callback for both, native per-channel buffers in the driver's sample format,+and the buffer size usually dictated by the driver's own control panel. Preferences →+Audio (`src/managed/Nota.App/PreferencesWindow.cs`) has output / input / sample rate /+buffer size rows plus the WASAPI-exclusive switch on Windows. `BUILD.md` currently says+"ASIO is not supported yet". The core engine must stay JUCE-free, so JUCE's ASIO device+type is not an option.++## Clarifications++### Session 2026-10-28++- Q: Is one stereo pair per direction enough, or must more than two inputs be available at once? → A: One output pair and one input pair; multi-input recording is a later feature.+- Q: ASIO in every official Windows build, or only opt-in builds where the builder supplies the SDK? → A: Every official build; the SDK ships under its GPLv3 option with the third-party row, notice and PR rationale.++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Play through an ASIO driver (Priority: P1)++A Windows user with an audio interface (Focusrite, RME, MOTU, Behringer…) opens+Preferences → Audio, switches the audio system from WASAPI to ASIO, picks their+interface's ASIO driver, and Nota plays through it at the driver's buffer size — far+lower and steadier latency than WASAPI shared mode, with no other app muted by Nota's+choice (that is the driver's business).++**Why this priority**: This is the whole point — without output through ASIO nothing+else in the feature has value. On its own it already serves the main audience.++**Independent Test**: On a Windows machine with any ASIO driver installed (a hardware+interface, or FlexASIO / ASIO4ALL), select ASIO and the driver, play a project and the+test tone; sound comes out of the interface and the Latency line shows the driver's+buffer size and sample rate.++**Acceptance Scenarios**:++1. **Given** at least one ASIO driver is installed, **When** the user opens Preferences →+ Audio, **Then** they can choose ASIO as the audio system and see every installed+ ASIO driver by name.+2. **Given** ASIO and a working driver are selected, **When** the project plays, **Then**+ audio comes out of the driver's output channels and the Latency line reports the+ driver's buffer size, sample rate and resulting latency.+3. **Given** the user selected ASIO and a driver, **When** they quit and relaunch Nota,+ **Then** the same audio system and driver are reopened.+4. **Given** no ASIO driver is installed, **When** the user opens Preferences → Audio,+ **Then** ASIO is shown as unavailable with a short hint (install the interface's+ driver, or a generic one), and WASAPI stays selected.++---++### User Story 2 - Record through the same ASIO driver (Priority: P1)++The same user arms an audio track and records their microphone or guitar through the+interface's inputs while monitoring the project, all on the one ASIO driver, with+recordings landing in time with the playback.++**Why this priority**: People buy interfaces to record. ASIO output with input still on+WASAPI (another device, another clock) would drift and defeat the purpose.++**Independent Test**: With ASIO selected, record-arm a track, record a click played back+into an input with a loopback cable; the recorded click lines up with the source within+the reported latency compensation.++**Acceptance Scenarios**:++1. **Given** ASIO is the audio system, **When** the user opens the Input row, **Then** it+ offers the selected driver's input channels and nothing from other drivers or WASAPI.+2. **Given** a track is armed with ASIO input, **When** the user records, **Then** the+ captured audio is sample-aligned with playback after the engine's usual latency+ compensation, with no drift over a 10-minute take.+3. **Given** the driver has no inputs, **When** the user arms a track, **Then** recording is+ unavailable with the same message Nota shows today when there is no input device.++---++### User Story 3 - Change buffer size and sample rate (Priority: P2)++The user wants lower latency for tracking or a bigger buffer for mixing. They press+"Driver settings…" in Preferences → Audio, the driver's own control panel opens, they+change the buffer size; Nota picks up the new size without a restart. Changing the+sample rate in Nota's own Sample rate row asks the driver for that rate.++**Why this priority**: Most ASIO drivers own the buffer size; without the control panel+and reset handling the user is stuck with whatever the driver started at, and a change in+the panel would silence or crash the app.++**Independent Test**: Open the driver panel from Preferences, change the buffer size while+the project plays; playback resumes within a couple of seconds and the Latency line shows+the new size. Change Nota's sample rate row; the driver switches rate and playback is at+correct pitch.++**Acceptance Scenarios**:++1. **Given** ASIO is selected, **When** the user presses "Driver settings…", **Then** the+ driver's own control panel opens.+2. **Given** the project is playing, **When** the driver asks the host to reset (buffer+ size, sample rate or channel layout changed in its panel or on the hardware), **Then**+ Nota restarts the driver with the new settings within 2 seconds, keeps the project+ state, and the Latency line updates.+3. **Given** the driver supports the requested rate, **When** the user picks a sample rate,+ **Then** the driver runs at it; **given** it does not, **Then** the row reverts and the+ user is told the driver refused that rate.+4. **Given** ASIO is selected, **When** the user looks at the Buffer size row, **Then** it is+ read-only and shows the driver's size, pointing at "Driver settings…" (ASIO drivers+ decide the size themselves).++---++### User Story 4 - Recover when the driver fails (Priority: P2)++The interface is unplugged, the driver is held by another program, or a broken driver+fails to load. Nota does not hang or crash: it tells the user what happened and keeps+working through WASAPI until the driver is usable again.++**Why this priority**: ASIO drivers are third-party code of uneven quality and only one+program can usually hold one. A DAW that dies on a bad driver loses the user's work.++**Independent Test**: Select a driver, quit Nota, unplug the interface (or open the driver+in another DAW first), launch Nota; it starts on WASAPI with a status message naming the+driver, and Preferences shows the reason.++**Acceptance Scenarios**:++1. **Given** the saved driver cannot be opened at launch, **When** Nota starts, **Then** it+ falls back to the system default WASAPI device, shows a status message naming the+ driver and the reason, and keeps ASIO as the user's saved choice for next time.+2. **Given** the driver stops responding or is unplugged while playing, **When** Nota+ detects it, **Then** it stops the driver, falls back to WASAPI within 3 seconds, and+ tells the user; the project and transport state are kept.+3. **Given** Nota is on the WASAPI fallback, **When** the user reselects the driver in+ Preferences and it opens, **Then** Nota moves back to ASIO.++---++### Edge Cases++- The driver uses a sample format other than 32-bit float (16-, 24- or 32-bit integer,+ little-endian): Nota converts to and from its internal float with correct scaling and+ no clicks; big-endian ("MSB") formats are refused with a clear message.+- The driver offers many channels (e.g. 18 in / 20 out): only the chosen stereo pair is+ used; all other output channels are fed silence, never garbage.+- The driver offers a mono-only output or input (one channel): mono output carries the+ mix down-summed, mono input is duplicated to both sides — the same as today's WASAPI+ handling of mono devices.+- The driver's buffer size is very small (32 frames) or very large (4096): playback works+ at both; very small sizes may raise CPU load and xruns are counted as today.+- The driver's buffer size changes in its panel while recording: the take is stopped+ cleanly up to the reset (what was recorded is kept), then the reset proceeds.+- The driver reports a latency or a resync: Nota uses the driver's reported input and+ output latency for recording compensation and the Latency line.+- Two ASIO drivers with the same name: both are listed, distinguishable (e.g. by a+ numeric suffix), and the saved choice reopens the right one.+- A 32-bit-only driver on 64-bit Windows: it is not listed (Nota cannot load it); a hint+ explains why a driver the user sees elsewhere may be missing.+- Generic wrappers (FlexASIO, ASIO4ALL) are just drivers: they appear in the list and+ work like any other.+- The user switches from ASIO back to WASAPI: the ASIO driver is released so other+ programs can use it, and the previous WASAPI output/input choices come back.+- The project is open on macOS or Linux after being saved on Windows with ASIO: nothing+ changes there — the audio system choice is a per-machine preference, not project state.++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: On Windows, Preferences → Audio MUST offer an audio system choice — WASAPI+ (today's behaviour, the default) or ASIO. The choice is hidden on macOS and Linux.+- **FR-002**: When ASIO is chosen, the app MUST list every installed ASIO driver that the+ running build can load, by the driver's name, and let the user pick one.+- **FR-003**: With ASIO selected, the engine MUST run the whole audio graph off the+ driver's buffer callback, so output and input share one clock and one callback.+- **FR-004**: The user MUST be able to choose which output channel pair carries the master+ and which input channel pair feeds recording, from the driver's named channels. One+ output pair and one input pair is the whole scope of this version; recording more than+ two inputs at once (per-track input channels on a multi-input interface) is a separate,+ later feature.+- **FR-005**: The engine MUST convert between its internal float samples and the driver's+ little-endian 16-, 24-, 32-bit integer and 32-bit float formats, in both directions,+ without allocating, locking or doing I/O inside the buffer callback.+- **FR-006**: Channels the user did not choose MUST receive silence on every buffer.+- **FR-007**: Preferences MUST offer a "Driver settings…" action that opens the selected+ driver's own control panel.+- **FR-008**: When ASIO is selected, the Buffer size row MUST show the driver's current+ size read-only; the Sample rate row MUST request the chosen rate from the driver and+ report a refusal.+- **FR-009**: When the driver requests a reset (buffer size, sample rate, channels or+ latency changed), the app MUST stop and reopen the driver off the audio thread with the+ new settings, preserving project and transport state, within 2 seconds.+- **FR-010**: Recording latency compensation and the Latency line MUST use the driver's+ reported input and output latencies.+- **FR-011**: If the selected driver cannot be loaded, initialised or started — at launch+ or on selection — or stops delivering buffers while running, the app MUST fall back to+ WASAPI with the system default devices, show a status message naming the driver and+ the reason, and keep ASIO as the saved preference.+- **FR-012**: Switching away from ASIO, quitting, or falling back MUST release the driver+ so other programs can open it.+- **FR-013**: The audio system, driver and channel choices MUST persist per machine in the+ app settings, alongside today's audio settings, and be restored at launch.+- **FR-014**: Xruns reported by the driver (overload / resync) MUST feed the existing+ dropout counter.+- **FR-015**: ASIO support MUST be part of every official Windows build (installer and+ CI), with no opt-in flag. The ASIO SDK is used under its GPLv3 option as a dependency+ of the shipped binary: a row in `LICENSES/third-party.md`, a notice in+ `LICENSES/THIRD-PARTY-NOTICES.md`, and the AGPL-compatibility rationale in the pull+ request, as CONTRIBUTING.md requires for a copyleft dependency.+- **FR-016**: The smoke test MUST keep passing on machines without any ASIO driver (CI),+ and the engine's ASIO sample-format conversion and reset handling MUST be covered by+ tests that do not need a real driver.+- **FR-017**: User-visible documentation MUST change: `BUILD.md` no longer says ASIO is+ unsupported; `CHANGELOG.md`, `FEATURES.md` and the user manual describe the new option.++### Key Entities++- **Audio system**: which Windows audio path the engine uses — WASAPI or ASIO. Per-machine+ preference.+- **ASIO driver**: an installed driver identified by its registered name and identity;+ has input channels, output channels, supported sample rates, a current buffer size, a+ sample format per channel, and reported latencies.+- **Channel selection**: the output pair carrying the master and the input pair feeding+ recording, identified by the driver's channel indices and shown by their names.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: With a hardware interface's ASIO driver at a 64-frame buffer, 48 kHz, a+ project of 16 tracks with built-in instruments and effects plays for 10 minutes with+ zero xruns on the reference Windows test machine.+- **SC-002**: Reported round-trip latency through ASIO at the driver's smallest supported+ buffer is at least 3× lower than WASAPI shared mode on the same machine and interface.+- **SC-003**: A user who has an ASIO driver installed can go from opening Preferences to+ hearing audio through ASIO in under 30 seconds, without reading documentation.+- **SC-004**: A buffer-size change in the driver panel during playback resumes audio+ within 2 seconds, 10 times out of 10, with no crash.+- **SC-005**: Launching with the saved driver missing or busy reaches a working, audible+ WASAPI session with an explanation, 10 times out of 10; no launch hangs longer than+ 5 seconds on a misbehaving driver.+- **SC-006**: A 10-minute loopback recording through ASIO shows no drift between the+ recorded and the played signal (offset stays within one sample after compensation).++## Assumptions++- ASIO is Windows-only; macOS (CoreAudio) and Linux (PulseAudio/ALSA) are unchanged.+- WASAPI stays the default audio system so nothing changes for users who never touch+ the setting, and it is the fallback whenever ASIO fails.+- Only one ASIO driver is open at a time (an ASIO limitation); Nota does not aggregate+ drivers or mix ASIO output with WASAPI input.+- The engine stays stereo internally in this version; ASIO adds channel *selection*, not+ multichannel routing (FR-004).+- Big-endian ("MSB") ASIO sample formats and DSD are out of scope; they are practically+ unused on Windows.+- Only drivers matching the build's architecture can load: the x64 build lists 64-bit+ drivers; the ARM64 build lists native ARM64 drivers (few exist today) and shows an+ explanatory hint when there are none.+- Driver panels and driver loading run on the app's main/UI thread or a dedicated+ non-real-time thread; the buffer callback only converts and renders.+- The Steinberg ASIO SDK's GPLv3 option is compatible with AGPL-3.0-only (GPLv3 §13 /+ AGPLv3 §13 permit combination); this still requires the explicit dependency decision+ CONTRIBUTING.md asks for, recorded in `LICENSES/third-party.md` and in the pull request.+ The exact current SDK license terms are re-checked at plan time.+- The audio system choice is a machine preference stored with today's audio settings,+ never in the project file.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [ ] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [ ] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned — **ASIO SDK (GPLv3 option); row + rationale required, see FR-015**+- [ ] Audio-thread impact considered: no alloc / lock / I/O on the audio thread (AR-6), command queue for data in (AR-4), immutable snapshots for structural edits (AR-5) — the ASIO buffer callback becomes the audio thread; driver reset/restart happens off it+- [ ] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/` — driver list, channel lists, audio system choice and "open driver panel" are new C ABI calls+- [ ] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest` — must pass with no ASIO driver present (FR-016)+- [ ] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned (and FEATURES.md / user docs via the nota-features / nota-docs skills when working with an agent that has them)+- [ ] UI change → follows `DESIGN.md` (Studio design language)diff --git a/specs/049-asio-backend/tasks.md b/specs/049-asio-backend/tasks.mdnew file mode 100644index 00000000..02c60c6b--- /dev/null+++ b/specs/049-asio-backend/tasks.md@@ -0,0 +1,245 @@+---++description: "Task list for ASIO audio on Windows"+---++# Tasks: ASIO audio on Windows++**Input**: Design documents from `specs/049-asio-backend/`++**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md), [data-model.md](data-model.md), [contracts/](contracts/), [quickstart.md](quickstart.md)++**Tests**: Requested by the spec (FR-016) — the device-free `nota_asio_selftest()` driven by+a fake driver, called from `tests/Nota.SmokeTest`. Each story adds its own cases to it.+Real-driver checks are manual ([quickstart.md](quickstart.md)).++**Organization**: Tasks are grouped by user story so each story can be implemented and tested on its own.++## Format: `[ID] [P?] [Story] Description`++- **[P]**: Can run in parallel (different files, no dependencies)+- **[Story]**: Which user story this task belongs to (US1–US4)++## Path Conventions++- Engine root: `src/native/nota.engine/` (abbreviated `engine/` below). C ABI: `engine/include/nota/nota_engine.h`+- ASIO core (all platforms): `engine/src/audio_io/asio/`; Windows layer: `engine/src/audio_io/windows/`+- Managed: `src/managed/<Project>/`; smoke test: `tests/Nota.SmokeTest/Program.cs`+- Every new source file starts with the two-line AGPL-3.0-only SPDX header (CONTRIBUTING.md)++---++## Phase 1: Setup (Shared Infrastructure)++**Purpose**: dependency, license record, build wiring++- [X] T001 Add a `CPMAddPackage(NAME asiosdk URL "https://download.steinberg.net/sdk_downloads/ASIO-SDK_2.3.4_2025-10-15.zip" URL_HASH "SHA256=<computed>" DOWNLOAD_ONLY YES)` block guarded by `if(WIN32)` in `engine/cmake/dependencies.cmake`; compute the SHA256 from the downloaded zip and pin it (research R1)+- [X] T002 [P] Add the ASIO SDK row to `LICENSES/third-party.md` (version 2.3.4, purpose "ASIO driver I/O (Windows)", license **GPL-3.0 (dual: proprietary / GPLv3, used under GPLv3)**, status "✅ in use — CPM pinned zip, headers only, Windows only — see note 8") and write note 8: GPLv3 §13 / AGPLv3 §13 combination, headers-only use, no logo shipped, "ASIO" used only as the driver-type name per Steinberg's trademark rules, the source of the license text (SDK `LICENSE.txt`, steinberg.net/developers/asiosdk-open)+- [X] T003 [P] Add the ASIO SDK notice (copyright "(c) 2025, Steinberg Media Technologies GmbH", GPLv3, where to get it) to `LICENSES/THIRD-PARTY-NOTICES.md`; confirm the GPLv3 text is in `LICENSES/` (add `GPL-3.0-only.txt` if missing)+- [X] T004 In `engine/CMakeLists.txt` add `src/audio_io/asio/*.cpp` to the engine sources on every platform and `src/audio_io/windows/*.cpp` plus `${asiosdk_SOURCE_DIR}/common` include path under `WIN32`; define `NOTA_HAS_ASIO=1` on Windows only++---++## Phase 2: Foundational (Blocking Prerequisites)++**Purpose**: the platform-independent ASIO core, the config/interface hooks and the self-test entry point that every story builds on++**⚠️ CRITICAL**: no user story work can begin until this phase is complete++- [X] T005 [P] Create `engine/src/audio_io/asio/AsioSampleFormat.h/.cpp`: our own enum mirroring the ASIO sample-type values (so non-Windows builds need no SDK), and RT-safe pure functions `toFloat(const void* src, AsioSample type, float* dst, int frames, int stride)` / `fromFloat(...)` for Int16LSB, Int24LSB (packed 3-byte), Int32LSB, Int32LSB16/18/20/24, Float32LSB, Float64LSB; integer→float scales by `1/2^(bits-1)`, float→integer clamps to [-1, 1) and rounds, no dither; `isSupported(type)` returns false for every MSB and DSD type (research R6)+- [X] T006 [P] Create `engine/src/audio_io/asio/AsioDriverApi.h`: abstract interface with the IASIO subset AsioSession uses — `init`, `getDriverName`, `getChannels`, `getBufferSize`, `canSampleRate`, `getSampleRate`, `setSampleRate`, `getChannelInfo`, `createBuffers`, `disposeBuffers`, `start`, `stop`, `getLatencies`, `controlPanel`, `outputReady` — plus a `Callbacks` struct (bufferSwitch, sampleRateDidChange, asioMessage) (research R3, R11)+- [X] T007 Create `engine/src/audio_io/asio/AsioSession.h/.cpp`: owns one `AsioDriverApi`, implements the state machine in data-model.md (`Closed → Loaded → Prepared → Running`, `Failed(reason)` with reasons `NotInstalled, LoadFailed, InitFailed, UnsupportedFormat, NoOutputs, Timeout, Stopped`), allocates all conversion buffers in `prepare()` (never in the callback), and in `bufferSwitch(index)`: checks an `active_` atomic, converts the chosen input pair to interleaved stereo and calls the registered `InputCallback`, calls the `RenderCallback`, converts the stereo result to the chosen output pair, writes zeros to every other output channel each switch (FR-006), down-sums to a mono output / duplicates a mono input (spec edge case), calls `outputReady()` when the driver supports it. A single static `AsioSession* g_active` routes the callbacks (research R4). `asioMessage` only sets atomics (`resetRequested_`, `xrunPending_`) and answers `kAsioSelectorSupported` / `kAsioEngineVersion` / `kAsioSupportsTimeInfo` (AR-6) (depends on T005, T006)+- [X] T008 Create `engine/src/audio_io/asio/FakeAsioDriver.h/.cpp`: test-only `AsioDriverApi` with configurable channel counts and names, sample type per channel, buffer size, sample rates, input/output latencies, a scripted input signal, and switches for "init fails", "reports reset request", "stops calling back"; drives `bufferSwitch` from its own thread or synchronously via `pump(n)` and records what the host wrote to every output channel (depends on T006)+- [X] T009 [P] Extend `AudioConfig` in `engine/src/audio_io/AudioConfig.h` with `AudioSystem audioSystem = AudioSystem::Wasapi` (`enum class AudioSystem { Wasapi, Asio }`), `std::string asioDriverClsid`, `std::string asioDriverName`, `int32_t asioOutputPair = 0`, `int32_t asioInputPair = 0`; read/write them in `engine/src/audio_io/ConfigJson.cpp` as `"audioSystem": "wasapi" | "asio"`, `"asioDriver"`, `"asioDriverName"`, `"asioOutputPair"`, `"asioInputPair"` — missing keys mean today's behaviour (WASAPI); `audioSystem` reads as Wasapi on non-Windows (data-model.md, research R10)+- [X] T010 [P] Add to `AudioBackend` in `engine/src/audio_io/AudioBackend.h`: `virtual int32_t inputLatencyFrames() const { return 0; }`, `virtual int32_t outputLatencyFrames() const { return 0; }`, `virtual bool sharesInputClock() const { return false; }`, `virtual int32_t pollDeviceEvent() { return 0; }`, `virtual const char* fallbackReason() const { return ""; }` — CoreAudio and miniaudio keep the defaults (research R7, R8)+- [X] T011 Add `NOTA_API int32_t nota_asio_selftest(void);` to `engine/include/nota/nota_engine.h` and implement it in `engine/src/abi/nota_engine_audio.cpp` as a runner over `AsioSession` + `FakeAsioDriver` that returns 1 only if every case passes; start with the format cases: round-trip of ±full-scale, 0 and a sine through every supported type within 1 LSB, MSB/DSD refused (depends on T005, T007, T008)+- [X] T012 Mirror the self-test in managed code — `NativeMethods.AsioSelfTest` in `src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.cs`, `public static bool AsioSelfTest()` in `src/managed/Nota.Infrastructure/Interop/NotaEngine.Audio.cs` — and add `Check(NotaEngine.AsioSelfTest(), "ASIO self-test (fake driver): formats, pair routing, duplex, reset, fallback, latency");` in `tests/Nota.SmokeTest/Program.cs` next to the other device-free self-tests (depends on T011)++**Checkpoint**: `scripts/build.sh` green on macOS with the new core compiled and its format cases passing++---++## Phase 3: User Story 1 — Play through an ASIO driver (Priority: P1) 🎯 MVP++**Goal**: choose ASIO + a driver in Preferences, hear the project through the chosen output pair, settings survive a relaunch++**Independent Test**: on Windows with any ASIO driver (or FlexASIO), select ASIO and the driver, play the test tone — sound on the chosen pair, Latency line shows the driver's buffer and rate (quickstart steps 1–3)++### Tests for User Story 1++- [X] T013 [P] [US1] Add self-test cases in `engine/src/abi/nota_engine_audio.cpp`: a fake 8-out driver with output pair 2 gets the render on channels 2/3 and exact zeros on 0,1,4–7 for 100 switches; a 1-out driver gets the mono down-sum; Int32LSB and Float32LSB drivers both produce the expected samples++### Implementation for User Story 1++- [X] T014 [P] [US1] Create `engine/src/audio_io/windows/AsioDriverList.h/.cpp`: enumerate `HKEY_LOCAL_MACHINE\SOFTWARE\ASIO\*` (native registry view only — no `WOW6432Node`, so 32-bit drivers are skipped) reading `CLSID` and `Description`; return `AsioDriverInfo { clsid, name, displayName }` with duplicate names suffixed " (2)", " (3)" for display; `find(clsid, name)` matches CLSID first, then name (research R3, R10)+- [X] T015 [US1] Create `engine/src/audio_io/windows/ComAsioDriver.h/.cpp`: an `AsioDriverApi` over `IASIO` (`iasiodrv.h`) created with `CoCreateInstance(clsid, nullptr, CLSCTX_INPROC_SERVER, clsid, …)`; all calls run on one dedicated control thread initialised with `CoInitializeEx(COINIT_APARTMENTTHREADED)` that pumps messages, each call posted and waited on with a timeout (5 s for load/init, 2 s otherwise) — a timeout returns `Failed(Timeout)` and abandons the driver object (research R4, SC-005) (depends on T006)+- [X] T016 [US1] Create `engine/src/audio_io/windows/AsioBackend.h/.cpp` implementing `AudioBackend` over a shared `AsioSession`: `start()` loads the configured driver, applies the requested sample rate if non-zero and supported, ignores `bufferFrames` (driver decides, FR-008), opens the output pair, starts; reports `sampleRate()`, `bufferFrames()`, `outputLatencyFrames()`; `stop()` stops and disposes and releases the driver (FR-012); xruns from `kAsioOverload`/resync feed `setXrunCallback` (FR-014) (depends on T007, T015)+- [X] T017 [US1] Change `engine/src/audio_io/AudioBackendFactory.h/.cpp` so `createAudioBackend(const AudioConfig&)` returns `AsioBackend` when `NOTA_HAS_ASIO` and `audioSystem == Asio`, else today's backend; keep one process-wide `AsioSession` shared by the ASIO facades; recreate the backend in `Engine::applyAudioConfig()` (`engine/src/engine/Engine.cpp`) when the audio system changes (depends on T016)+- [X] T018 [US1] Add the system/driver/pair calls from `contracts/c-abi.md` to `engine/include/nota/nota_engine.h` and `engine/src/abi/nota_engine_audio.cpp`: `nota_audio_set_system`, `nota_audio_system`, `nota_audio_active_system`, `nota_audio_asio_available`, `nota_audio_asio_driver_count/_id/_name` (filled by `nota_audio_refresh_devices`), `nota_audio_set_asio_driver`, `nota_audio_asio_driver`, `nota_audio_asio_channel_count/_name`, `nota_audio_set_asio_pair`, `nota_audio_asio_pair`, `nota_audio_output_latency_frames`; on macOS/Linux every one is a no-op (counts 0, available 0, setters `NOTA_OK`) (depends on T009, T017)+- [X] T019 [US1] Mirror them in `src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.cs`, `src/managed/Nota.Infrastructure/Interop/NotaEngine.Audio.cs` and `src/managed/Nota.Application/Engine/IAudioEngine.cs` (`AudioSystem`, `ActiveAudioSystem`, `AsioAvailable`, `AsioDrivers`, `SetAsioDriver`, `AsioChannels(bool input)`, `AsioPair(bool input)`, `SetAsioPair`, `OutputLatencyFrames`); update any test doubles implementing `IAudioEngine` (depends on T018)+- [X] T020 [US1] In `src/managed/Nota.App/PreferencesWindow.cs` (Windows only) add the "Audio system" row (WASAPI | ASIO) and, when ASIO is chosen, the Driver row and Output-pair row per `contracts/preferences-ui.md`, hiding the WASAPI Output/Input/Exclusive rows; pairs are labelled from the driver's channel names ("Out 1 + 2"); each change calls `Apply()`; with no driver installed the ASIO option is disabled with the caption "No ASIO driver found. Install your interface's driver, or a generic one such as FlexASIO." and an ARM64-specific variant of the hint; follow DESIGN.md (nota-design skill) (depends on T019)+- [X] T021 [US1] Update `UpdateLatency()` in `src/managed/Nota.App/PreferencesWindow.cs` and the apply status in `src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.cs` to show "ASIO · <driver>" and the output latency from `OutputLatencyFrames` when ASIO is active+- [X] T022 [US1] Add a smoke check in `tests/Nota.SmokeTest/Program.cs` that the new ABI is a safe no-op off Windows (`AsioAvailable == false`, driver count 0, setting system ASIO + apply leaves the active system WASAPI/native) and that `audio.json` keys round-trip through the engine's config load/save without touching the real backend++**Checkpoint**: US1 works on its own — ASIO playback, persistence, no-driver hint++---++## Phase 4: User Story 2 — Record through the same ASIO driver (Priority: P1)++**Goal**: inputs come from the same driver and clock; takes are aligned using the driver's reported latency++**Independent Test**: loopback a click out 1/2 → in 1/2, record 10 minutes — recorded clicks align with the source within one sample (quickstart step 6)++### Tests for User Story 2++- [X] T023 [P] [US2] Add self-test cases in `engine/src/abi/nota_engine_audio.cpp`: with a fake duplex driver the input callback for switch *n* is called before render of switch *n*; input pair 2 of a 4-in driver reaches the callback; a mono input is duplicated; a take recorded through the fake driver with input latency 100 and output latency 150 frames starts 250 frames earlier than the uncompensated position++### Implementation for User Story 2++- [X] T024 [P] [US2] Create `engine/src/audio_io/windows/AsioInput.h/.cpp` implementing `AudioInput` over the shared `AsioSession`: `start(cb, device)` registers the callback with the session (it never opens a second driver), ignores `device`, reports the session's sample rate; `stop()` unregisters; `inputLatencyFrames()` via the session (research R2) (depends on T007)+- [X] T025 [US2] Make `createAudioInput()` in `engine/src/audio_io/AudioBackendFactory.cpp` return `AsioInput` bound to the shared session when ASIO is the active system (after fallback, the WASAPI input), and make `AsioBackend::inputLatencyFrames()` / `sharesInputClock()` (true) report the driver values in `engine/src/audio_io/windows/AsioBackend.cpp` (depends on T017, T024)+- [X] T026 [US2] In `engine/src/engine/Engine_Recording.cpp`, when a hardware-input take is materialised, shift its start earlier by `backend_->inputLatencyFrames() + backend_->outputLatencyFrames()` (0 on every non-ASIO backend, so no behaviour change there) (research R7)+- [X] T027 [US2] In `Engine::pullMonitorInput` (`engine/src/engine/Engine_Recording.cpp`) use no cushion when `backend_->sharesInputClock()` — pop exactly the current block (research R8)+- [X] T028 [US2] Add `nota_audio_input_latency_frames` to `engine/include/nota/nota_engine.h` / `engine/src/abi/nota_engine_audio.cpp` and `InputLatencyFrames` to the managed interop and `IAudioEngine`; show the round trip on the Latency line when an input is in use (`src/managed/Nota.App/PreferencesWindow.cs`)+- [X] T029 [US2] Add the Input-pair row for ASIO in `src/managed/Nota.App/PreferencesWindow.cs`, listing only the open driver's input pairs; a driver with no inputs shows "No inputs on this driver" and recording reports the existing no-input message++**Checkpoint**: US1 + US2 — play and record through one ASIO driver++---++## Phase 5: User Story 3 — Change buffer size and sample rate (Priority: P2)++**Goal**: open the driver's panel; driver resets are picked up within 2 s without a restart; sample-rate requests are honoured or refused visibly++**Independent Test**: change the buffer in the driver panel during playback — audio resumes ≤ 2 s and the Latency line updates, 10 of 10 times (quickstart steps 4–5)++### Tests for User Story 3++- [X] T030 [P] [US3] Add self-test cases in `engine/src/abi/nota_engine_audio.cpp`: a fake `kAsioResetRequest` / `kAsioBufferSizeChange` / `kAsioLatenciesChanged` / `sampleRateDidChange` each produce exactly one `RESET_REQUESTED` event; a driver whose buffer size changes without a message is detected at the next switch and also produces one; an unsupported `setSampleRate` returns a refusal and leaves the running rate unchanged++### Implementation for User Story 3++- [X] T031 [US3] In `AsioSession` (`engine/src/audio_io/asio/AsioSession.cpp`) turn reset-type messages and an unexpected buffer size into `resetRequested_`, exposed through `AsioBackend::pollDeviceEvent()` returning `1` once per request (clear on read) (data-model.md "Device event")+- [X] T032 [US3] Add `nota_audio_poll_device_event` and `nota_audio_asio_open_control_panel` (posted to the control thread, returns immediately) to `engine/include/nota/nota_engine.h` / `engine/src/abi/nota_engine_audio.cpp`, and `PollDeviceEvent()` / `OpenAsioControlPanel()` to the managed interop and `IAudioEngine`+- [X] T033 [US3] In `MainWindowViewModel`'s engine tick (`src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.cs`, next to `ReportDropouts()`), poll the device event; on `RESET_REQUESTED` remember play state + position, run `ApplyAudioSettings()`, then resume playback at the same position if it was playing; status "Audio: driver settings changed · <n> frames" (FR-009)+- [X] T034 [US3] In `src/managed/Nota.App/PreferencesWindow.cs` add the "Driver settings…" button (enabled only while ASIO runs), make Buffer size read-only text "<n> frames (set in the driver's settings)" under ASIO, and on a refused sample rate revert the row and show the caption "The driver doesn't support <rate>" (FR-007, FR-008)+- [X] T035 [US3] Make `AsioBackend::start()` (`engine/src/audio_io/windows/AsioBackend.cpp`) report a refused sample-rate request so `nota_audio_apply` can surface it (the session keeps the driver's current rate instead of failing)++**Checkpoint**: US1–US3 — reset handling and the driver panel work++---++## Phase 6: User Story 4 — Recover when the driver fails (Priority: P2)++**Goal**: a missing, busy, broken or vanished driver never hangs or crashes Nota; it falls back to WASAPI with a reason and returns to ASIO when possible++**Independent Test**: launch with the saved driver unplugged or held by another DAW — Nota starts on WASAPI within 5 s, the status names the driver and reason, Preferences still shows ASIO (quickstart steps 7–9)++### Tests for User Story 4++- [X] T036 [P] [US4] Add self-test cases in `engine/src/abi/nota_engine_audio.cpp`: fake "init fails" → `Failed(InitFailed)` with a non-empty reason; unsupported (MSB) output type → `Failed(UnsupportedFormat)`; "stops calling back" while running → `DRIVER_FAILED` event within 2 s of the last callback; after `stop()` a late `bufferSwitch` from the fake is ignored (no render call)++### Implementation for User Story 4++- [X] T037 [US4] Add a watchdog in `AsioSession` (`engine/src/audio_io/asio/AsioSession.cpp`): the buffer callback stores a tick; the control thread checks it every 250 ms while Running and moves to `Failed(Stopped)` after 2 s without a callback, raising `DRIVER_FAILED` (data-model.md)+- [X] T038 [US4] In `Engine::start()` / `applyAudioConfig()` (`engine/src/engine/Engine.cpp`): if the ASIO backend fails to start, keep its reason, create the miniaudio backend and start it with system defaults (`outputDeviceUid = ""`, rate/buffer 0), keep `config_.audioSystem = Asio` in the saved config (FR-011), and make `nota_audio_apply` return `NOTA_OK` unless nothing at all opened+- [X] T039 [US4] Add `nota_audio_fallback_reason` to `engine/include/nota/nota_engine.h` / `engine/src/abi/nota_engine_audio.cpp` (driver name + human reason, "" when not in fallback) and `AudioFallbackReason` to the managed interop and `IAudioEngine`+- [X] T040 [US4] In `src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.cs`: after launch and after every apply, if `AudioSystem == Asio && ActiveAudioSystem != Asio` set status "ASIO driver ‘<name>’ couldn't start — using WASAPI. <reason>"; on a `DRIVER_FAILED` event run `ApplyAudioSettings()` (which falls back), keeping the transport position+- [X] T041 [US4] In `src/managed/Nota.App/PreferencesWindow.cs` show "ASIO unavailable (<reason>) → WASAPI" on the Latency line while in fallback; reselecting the driver re-applies and returns to ASIO when it opens (US4-3)++**Checkpoint**: all four stories work independently++---++## Phase 7: Polish & Cross-Cutting Concerns++- [X] T042 [P] Update `BUILD.md` § Windows platform details: audio is WASAPI or ASIO (SDK fetched by CPM, GPLv3); remove "ASIO is not supported yet"; mention FlexASIO for testing without hardware+- [X] T043 [P] Update the platform table and § Audio engine in `ARCHITECTURE.md` (Windows: "WASAPI via miniaudio, or ASIO (`audio_io/windows/`)"; one shared duplex session behind `AudioBackend` + `AudioInput`)+- [X] T044 [P] Refresh the header comments of `engine/src/audio_io/AudioBackend.h`, `AudioInput.h`, `AudioConfig.h` and the C ABI block comment in `engine/include/nota/nota_engine.h` (they still say "CoreAudio" / "~/Library" only)+- [X] T045 Review the buffer-switch path in `engine/src/audio_io/asio/AsioSession.cpp` against AR-6 (no allocation, locks, logging or `std::function` copies; callbacks stored before start) and against misbehaving drivers (late callbacks, double `start`)++### Nota closing tasks *(always include — these are the PR gates)*++- [X] T046 Run `scripts/build.sh` (macOS) until native + managed + smoke are green; run `pwsh scripts/build-win.ps1` on Windows (or confirm the Windows CI job) so the SDK fetch and the `windows/` layer compile and the smoke test passes without an ASIO driver+ - *2026-10-29: green on macOS, Linux and Windows CI (windows-2022: SDK fetch, `audio_io/windows/` compiled, smoke incl. `nota_asio_selftest` passed).*+- [X] T047 AGPL-3.0-only SPDX two-line header on every new source file under `engine/src/audio_io/asio/` and `engine/src/audio_io/windows/`+- [X] T048 New dependency: ASIO SDK row + note 8 in `LICENSES/third-party.md` and notice in `LICENSES/THIRD-PARTY-NOTICES.md` done (T002, T003); the PR description carries the GPLv3 ↔ AGPLv3 rationale (nota-pr skill)+ - *Register row, note 8, notice, `LICENSES/GPL-3.0-only.txt`; GPLv3 ↔ AGPLv3 rationale in the PR description.*+- [X] T049 `CHANGELOG.md` `[Unreleased]` entry under Added: ASIO on Windows — choose the driver and channel pair, driver settings, low-latency recording with latency compensation, automatic WASAPI fallback+- [X] T050 FEATURES.md via the `nota-features` skill (Windows platform line + Preferences → Audio); user manual EN + RU via the `nota-docs` skill (Preferences → Audio page, Windows setup); shortcuts: N/A+- [X] T051 Engine behaviour change → smoke test covers it via `nota_asio_selftest` (T011–T013, T023, T030, T036) and the ABI no-op check (T022)+- [ ] T052 Manual validation on a Windows machine per `quickstart.md` steps 1–10; record results (or "pending — no Windows hardware") in the PR+ - *Pending — no Windows hardware in this session.*++---++## Dependencies & Execution Order++### Phase Dependencies++- **Setup (Phase 1)**: none. T004 needs T001 for the include path+- **Foundational (Phase 2)**: after Setup; blocks all stories. T007 needs T005 + T006; T008 needs T006; T011 needs T005/T007/T008; T012 needs T011+- **US1 (Phase 3)**: after Foundational — the MVP+- **US2 (Phase 4)**: after Foundational; T025 needs US1's factory change (T017). Independently testable through the fake driver+- **US3 (Phase 5)**: after US1 (needs a running ASIO backend and the Preferences rows)+- **US4 (Phase 6)**: after US1 (needs the ASIO backend to fail from)+- **Polish (Phase 7)**: after the stories you ship++### Within Each Story++- Self-test cases first (they fail until the code lands), then engine, then ABI, then managed, then UI++### Parallel Opportunities++- T002 and T003 alongside T001+- T005, T006, T009, T010 together (different files)+- In US1: T013 and T014 together, then T015+- In US2: T023 and T024 together+- US3 and US4 can run in parallel once US1 is done (different files except `AsioSession.cpp` — T031 and T037 touch it; do them one after the other)+- T042, T043, T044 together++---++## Parallel Example: Phase 2++```bash+Task: "AsioSampleFormat conversions in engine/src/audio_io/asio/AsioSampleFormat.cpp"+Task: "AsioDriverApi interface in engine/src/audio_io/asio/AsioDriverApi.h"+Task: "AudioConfig fields + ConfigJson keys in engine/src/audio_io/AudioConfig.h, ConfigJson.cpp"+Task: "AudioBackend latency/clock virtuals in engine/src/audio_io/AudioBackend.h"+```++## Parallel Example: User Story 1++```bash+Task: "Self-test cases for pair routing and silence in engine/src/abi/nota_engine_audio.cpp"+Task: "Registry driver enumeration in engine/src/audio_io/windows/AsioDriverList.cpp"+```++---++## Implementation Strategy++### MVP First (User Story 1 only)++1. Phase 1 + Phase 2 — the core compiles and its format tests pass on macOS+2. Phase 3 — ASIO playback with driver choice and persistence+3. **Stop and validate** on Windows (quickstart steps 1–3), even before recording exists++### Incremental Delivery++1. Setup + Foundational → core verified by the fake driver+2. + US1 → playback (MVP)+3. + US2 → recording, the reason people buy interfaces — ship US1 + US2 together if possible+4. + US3 → driver panel and resets+5. + US4 → robust fallback+6. Polish + gates → one PR (constitution V: the pieces are unusable apart)++---++## Notes++- Windows-only code can only be compiled in CI or on a Windows machine from here; keep `windows/` thin and the logic in `asio/`, where the fake driver tests it on every platform+- Don't commit — the user reviews and commits (project memory)+- [P] = different files, no dependency on an unfinished taskdiff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex 823ddb20..a6db11f1 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -13,6 +13,7 @@using System;using System.Collections.Generic;using System.Linq;+using System.Runtime.InteropServices;using Avalonia;using Avalonia.Collections;using Avalonia.Controls;@@ -166,6 +167,13 @@ public sealed partial class PreferencesWindow : NotaWindowJobs.Changed += RenderStoreLists;Jobs.ProgressChanged += UpdateDock;Closed += (_, _) => { StopTests(); Jobs.Changed -= RenderStoreLists; Jobs.ProgressChanged -= UpdateDock; };+ // The driver restarted on its own (its panel changed the buffer, or it failed over to+ // WASAPI): the Audio pane's rows and latency describe the old state — rebuild them.+ if (_main is not null)+ {+ _main.AudioDeviceRestarted += OnAudioDeviceRestarted;+ Closed += (_, _) => _main.AudioDeviceRestarted -= OnAudioDeviceRestarted;+ }Select(0);EnsureStoreLoading();UpdateDock();@@ -308,11 +316,26 @@ public sealed partial class PreferencesWindow : NotaWindowUpdateLatency();var latency = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { _latencyValue, _latencyDetail } };- var device = new List<Control>+ var device = new List<Control>();+ // Audio system (Windows, specs/049): WASAPI, or ASIO through the interface's own driver.+ bool asioUi = OperatingSystem.IsWindows() && engine.AsioAvailable;+ bool asio = asioUi && engine.AudioSystem == AudioSystem.Asio;+ if (asioUi) AudioSystemRows(device, engine, asio);+ if (asio)+ {+ AsioRows(device, engine, srCombo);+ device.Add(Row("Latency", latency));+ var asioBody = Sections(+ Section("Audio device", 6, device.ToArray()),+ Section("Test", 8, TestToneRow(), CpuCheckRow(engine)));+ _loading = false;+ return asioBody;+ }+ device.AddRange(new[]{Row("Output", outputCombo), Row("Input", inputCombo),Row("Sample rate", srCombo), Row("Buffer size", bufCombo),- };+ });// WASAPI exclusive (Windows only): lets Nota own the output device for the lowest// latency, at the cost of muting other apps. The device then dictates the sample rate /// buffer, so those are ignored while it's on. If the device refuses exclusive (busy /@@ -336,6 +359,154 @@ public sealed partial class PreferencesWindow : NotaWindowreturn body;}+ // "Audio system [WASAPI | ASIO]". With no ASIO driver installed the ASIO item is disabled+ // and a caption says what to install (contracts/preferences-ui.md).+ private void AudioSystemRows(List<Control> device, IAudioEngine engine, bool asio)+ {+ var drivers = engine.AsioDrivers();+ var combo = Combo(150);+ combo.Items.Add("WASAPI");+ combo.Items.Add(new ComboBoxItem { Content = "ASIO", IsEnabled = drivers.Count > 0 || asio });+ combo.SelectedIndex = asio ? 1 : 0;+ combo.SelectionChanged += (_, _) =>+ {+ if (_loading || combo.SelectedIndex < 0) return;+ bool toAsio = combo.SelectedIndex == 1;+ engine.SetAudioSystem(toAsio ? AudioSystem.Asio : AudioSystem.Wasapi);+ if (toAsio && engine.AsioDriver.Length == 0 && drivers.Count > 0) engine.SetAsioDriver(drivers[0].Uid);+ Apply();+ RebuildAudioPane();+ };+ device.Add(Row("Audio system", combo));+ if (drivers.Count == 0 && !asio)+ device.Add(Row("", Caption(RuntimeInformation.ProcessArchitecture == Architecture.Arm64+ ? "No ASIO driver found. Few interfaces ship an ARM64 ASIO driver yet — install one from your interface's maker, or a generic one such as FlexASIO."+ : "No ASIO driver found. Install your interface's driver, or a generic one such as FlexASIO.")));+ }++ // Driver · Output pair · Input pair · Sample rate · Buffer size (read-only) under ASIO.+ // Pairs come from the open driver, so they show once it runs; the buffer size is the+ // driver's own setting (FR-008), changed in its panel ("Driver settings…").+ private void AsioRows(List<Control> device, IAudioEngine engine, ComboBox srCombo)+ {+ bool running = engine.ActiveAudioSystem == AudioSystem.Asio;+ var drivers = engine.AsioDrivers();+ var driverCombo = Combo(280);+ string saved = engine.AsioDriver;+ int selected = -1;+ for (int i = 0; i < drivers.Count; i++)+ if (string.Equals(drivers[i].Uid, saved, StringComparison.OrdinalIgnoreCase)) selected = i;+ // A saved driver that is no longer installed stays visible as the choice, so picking+ // any installed one (even the only one) is a real change that stages and applies it.+ bool missing = saved.Length > 0 && selected < 0;+ int offset = missing ? 1 : 0;+ if (missing) driverCombo.Items.Add("Saved driver not found");+ foreach (var d in drivers) driverCombo.Items.Add(d.Name);+ driverCombo.SelectedIndex = missing ? 0 : selected >= 0 ? selected : (drivers.Count > 0 ? 0 : -1);+ driverCombo.SelectionChanged += (_, _) =>+ {+ int i = driverCombo.SelectedIndex - offset;+ if (_loading || i < 0 || i >= drivers.Count) return;+ engine.SetAsioDriver(drivers[i].Uid); // a different driver: start from its first pairs+ engine.SetAsioPair(false, 0);+ engine.SetAsioPair(true, 0);+ Apply();+ RebuildAudioPane();+ };+ // Running: the driver's own panel (a change there comes back as a reset event). In the+ // WASAPI fallback: try the driver again — it may be free or plugged in now (US4-3).+ var panel = Btn(running ? "Driver settings…" : "Try again");+ panel.IsEnabled = running || drivers.Count > 0;+ panel.Click += (_, _) =>+ {+ if (running) { engine.OpenAsioControlPanel(); return; }+ int i = driverCombo.SelectedIndex - offset; // retry the driver shown, not a stale one+ if (i >= 0 && i < drivers.Count) engine.SetAsioDriver(drivers[i].Uid);+ Apply();+ RebuildAudioPane();+ };+ device.Add(Row("Driver", new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { driverCombo, panel } }));++ if (running)+ {+ device.Add(Row("Output", PairCombo(engine, input: false, engine.AsioChannels(false))));+ var ins = engine.AsioChannels(true);+ device.Add(Row("Input", ins.Count > 0 ? PairCombo(engine, input: true, ins) : Caption("No inputs on this driver")));+ }++ // Sample rate is a request: a rate the driver refuses is reverted and explained (FR-007).+ // The view model remembers the refusal, so it also shows after an apply that waited for+ // the driver's panel to close (the pane is rebuilt then).+ var refused = Caption("");+ refused.Foreground = NotaPalette.Warning;+ void ShowRefusal()+ {+ double r = _main?.RefusedSampleRate ?? 0;+ refused.Text = r > 0 ? $"The driver doesn't support {NotaNum.Unit(r / 1000, "0.#", "kHz")}" : "";+ refused.IsVisible = r > 0;+ }+ ShowRefusal();+ srCombo.SelectionChanged += (_, _) =>+ {+ int i = srCombo.SelectedIndex;+ if (_loading || i <= 0 || engine.ActiveAudioSystem != AudioSystem.Asio) return;+ // The earlier handler applied the rate. A rate the driver refused is dropped by the+ // engine — the saved config goes back to "device default" — so the row follows it.+ ShowRefusal();+ if (_main?.RefusedSampleRate != SampleRates[i]) return;+ _loading = true;+ srCombo.SelectedIndex = 0;+ _loading = false;+ };+ device.Add(Row("Sample rate", new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, Children = { srCombo, refused } }));++ int buf = engine.NegotiatedBufferFrames;+ device.Add(Row("Buffer size", Caption(running && buf > 0+ ? $"{buf} frames (set in the driver's settings)"+ : "Set in the driver's settings")));+ }++ // Channel pairs of the open driver, labelled from its own names ("Out 1 + 2", "Analog 3 + 4");+ // a last odd channel is a mono pair.+ private ComboBox PairCombo(IAudioEngine engine, bool input, IReadOnlyList<string> channels)+ {+ var combo = Combo(280);+ var firsts = new List<int>();+ for (int c = 0; c < channels.Count; c += 2)+ {+ combo.Items.Add(PairLabel(channels[c], c + 1 < channels.Count ? channels[c + 1] : null));+ firsts.Add(c);+ }+ int staged = engine.AsioPair(input);+ combo.SelectedIndex = Math.Max(0, firsts.IndexOf(staged));+ combo.SelectionChanged += (_, _) =>+ {+ int i = combo.SelectedIndex;+ if (_loading || i < 0 || i >= firsts.Count) return;+ engine.SetAsioPair(input, firsts[i]);+ Apply();+ };+ return combo;+ }++ internal static string PairLabel(string a, string? b)+ {+ if (b is null) return a;+ int p = 0;+ while (p < a.Length && p < b.Length && a[p] == b[p]) p++;+ while (p > 0 && a[p - 1] != ' ') p--; // share whole words only ("Out 1" + "Out 2")+ return p > 0 ? $"{a} + {b[p..]}" : $"{a} + {b}";+ }++ // The audio pane's rows depend on the audio system and the open driver: rebuild it after+ // the combo that changed them has finished its event.+ private void RebuildAudioPane() => Dispatcher.UIThread.Post(() => Select(_selected));++ private void OnAudioDeviceRestarted()+ {+ if (_selected == 0) RebuildAudioPane(); // 0 = the Audio page+ }+private Control TestToneRow(){var button = Btn("Play test tone");@@ -427,11 +598,33 @@ public sealed partial class PreferencesWindow : NotaWindow}// "11.6 ms" · "512 frames @ 44.1 kHz" — the negotiated block, not the requested one.+ // Under ASIO the driver's own output latency, and the round trip when it has inputs.private void UpdateLatency(){if (_main is null || _latencyValue is null || _latencyDetail is null) return;double sr = _main.Engine.NegotiatedSampleRate;int buf = _main.Engine.NegotiatedBufferFrames;+ var eng = _main.Engine;+ if (OperatingSystem.IsWindows() && eng.AudioSystem == AudioSystem.Asio && sr > 0)+ {+ string khz = NotaNum.Unit(sr / 1000, "0.#", "kHz");+ if (eng.ActiveAudioSystem != AudioSystem.Asio)+ {+ string why = eng.AudioFallbackReason;+ _latencyValue.Text = buf > 0 ? NotaNum.Unit(buf / sr * 1000, "0.0", "ms") : "";+ _latencyDetail.Text = $"ASIO unavailable ({(why.Length > 0 ? why : "the driver didn't start")}) → WASAPI";+ }+ else+ {+ int outLat = eng.OutputLatencyFrames > 0 ? eng.OutputLatencyFrames : buf;+ int inLat = eng.InputLatencyFrames;+ string roundTrip = inLat > 0 ? $" · round trip {NotaNum.Unit((inLat + outLat) / sr * 1000, "0.0", "ms")}" : "";+ _latencyValue.Text = NotaNum.Unit(outLat / sr * 1000, "0.0", "ms");+ _latencyDetail.Text = $"ASIO · {buf} frames @ {khz}{roundTrip}";+ }+ _latencyValue.IsVisible = _latencyValue.Text.Length > 0;+ return;+ }string mode = OperatingSystem.IsWindows() && _main.Engine.AudioExclusiveFallback? " · exclusive refused → shared": OperatingSystem.IsWindows() && _main.Engine.GetAudioConfig().WasapiExclusive ? " · exclusive" : "";diff --git a/src/managed/Nota.App/Theme/NotaText.cs b/src/managed/Nota.App/Theme/NotaText.csindex 3b5b23fa..81f4eeef 100644--- a/src/managed/Nota.App/Theme/NotaText.cs+++ b/src/managed/Nota.App/Theme/NotaText.cs@@ -35,6 +35,7 @@ internal static class NotaText["PW"] = "PW", ["VCA"] = "VCA", ["VCF"] = "VCF", ["VCO"] = "VCO", ["THD"] = "THD",["BBD"] = "BBD", ["FET"] = "FET", ["RR"] = "RR", ["CC"] = "CC",["LUFS"] = "LUFS", ["USB"] = "USB", ["OK"] = "OK", ["DAW"] = "DAW",+ ["ASIO"] = "ASIO", ["WASAPI"] = "WASAPI",};/// <summary>A label in sentence case: "PRE-DELAY" → "Pre-delay", "LFO RATE" → "LFO rate",diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex 76942902..cd8227a8 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -413,6 +413,13 @@ public readonly record struct AutomationLaneInfo(AutomationTarget Target, int De/// <summary>An audio device: a stable UID (persistence key) and a display name (M7-1).</summary>public readonly record struct AudioDevice(string Uid, string Name);+/// <summary>The audio system on Windows (specs/049). Elsewhere always <see cref="Wasapi"/>, meaning+/// the platform's native backend.</summary>+public enum AudioSystem { Wasapi = 0, Asio = 1 }++/// <summary>What the audio driver asked for since the last poll (NotaAudioDeviceEvent).</summary>+public enum AudioDeviceEvent { None = 0, ResetRequested = 1, DriverFailed = 2 }+/// <summary>A MIDI input source: a stable UID (persistence key) and a display name (M7-2).</summary>public readonly record struct MidiDevice(string Uid, string Name);diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex c141cd2a..022eed73 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -1139,6 +1139,29 @@ public interface IAudioEngine : IDisposable/// <summary>True when no output device opened and the engine runs on a silent stand-in.</summary>bool AudioSilentFallback { get; }+ // --- ASIO (Windows; specs/049) -----------------------------------------+ // Staged like the device settings; ApplyAudio() persists and restarts. No-ops off Windows.+ AudioSystem AudioSystem { get; }+ /// <summary>What actually runs: WASAPI after a failed ASIO start fell back.</summary>+ AudioSystem ActiveAudioSystem { get; }+ bool AsioAvailable { get; }+ /// <summary>Installed ASIO drivers (re-scanned): Uid = CLSID, Name = display name.</summary>+ IReadOnlyList<AudioDevice> AsioDrivers();+ void SetAudioSystem(AudioSystem system);+ void SetAsioDriver(string id);+ string AsioDriver { get; }+ /// <summary>Channel names of the open ASIO driver; empty when ASIO isn't running.</summary>+ IReadOnlyList<string> AsioChannels(bool input);+ int AsioPair(bool input);+ void SetAsioPair(bool input, int firstChannel);+ bool OpenAsioControlPanel();+ /// <summary>The driver's panel is open: an apply now would wait for it, so hold it back.</summary>+ bool AsioPanelOpen { get; }+ AudioDeviceEvent PollDeviceEvent();+ string AudioFallbackReason { get; }+ int InputLatencyFrames { get; }+ int OutputLatencyFrames { get; }+// --- MIDI device settings (M7-2) ---------------------------------------bool IsMidiInputEnabled(string uid);void SetMidiInputEnabled(string uid, bool enabled);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.csindex 75985e63..88a63685 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Audio.cs@@ -78,6 +78,67 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_audio_silent_fallback")]internal static partial int AudioSilentFallback(IntPtr engine);+ // --- ASIO (Windows; specs/049) ---+ [LibraryImport(Lib, EntryPoint = "nota_audio_set_system")]+ internal static partial NotaResult AudioSetSystem(IntPtr engine, int system);++ [LibraryImport(Lib, EntryPoint = "nota_audio_system")]+ internal static partial int AudioSystem(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_audio_active_system")]+ internal static partial int AudioActiveSystem(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_audio_asio_available")]+ internal static partial int AudioAsioAvailable();++ [LibraryImport(Lib, EntryPoint = "nota_audio_asio_driver_count")]+ internal static partial int AudioAsioDriverCount();++ [LibraryImport(Lib, EntryPoint = "nota_audio_asio_driver_id")]+ internal static partial IntPtr AudioAsioDriverId(int index);++ [LibraryImport(Lib, EntryPoint = "nota_audio_asio_driver_name")]+ internal static partial IntPtr AudioAsioDriverName(int index);++ [LibraryImport(Lib, EntryPoint = "nota_audio_set_asio_driver", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial NotaResult AudioSetAsioDriver(IntPtr engine, string id);++ [LibraryImport(Lib, EntryPoint = "nota_audio_asio_driver")]+ internal static partial IntPtr AudioAsioDriver(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_audio_asio_channel_count")]+ internal static partial int AudioAsioChannelCount(IntPtr engine, int isInput);++ [LibraryImport(Lib, EntryPoint = "nota_audio_asio_channel_name")]+ internal static partial IntPtr AudioAsioChannelName(IntPtr engine, int isInput, int index);++ [LibraryImport(Lib, EntryPoint = "nota_audio_set_asio_pair")]+ internal static partial NotaResult AudioSetAsioPair(IntPtr engine, int isInput, int firstChannel);++ [LibraryImport(Lib, EntryPoint = "nota_audio_asio_pair")]+ internal static partial int AudioAsioPair(IntPtr engine, int isInput);++ [LibraryImport(Lib, EntryPoint = "nota_audio_asio_open_control_panel")]+ internal static partial NotaResult AudioAsioOpenControlPanel(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_audio_asio_panel_open")]+ internal static partial int AudioAsioPanelOpen(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_audio_poll_device_event")]+ internal static partial int AudioPollDeviceEvent(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_audio_fallback_reason")]+ internal static partial IntPtr AudioFallbackReason(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_audio_input_latency_frames")]+ internal static partial int AudioInputLatencyFrames(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_audio_output_latency_frames")]+ internal static partial int AudioOutputLatencyFrames(IntPtr engine);++ [LibraryImport(Lib, EntryPoint = "nota_asio_selftest")]+ internal static partial int AsioSelfTest();+[LibraryImport(Lib, EntryPoint = "nota_midi_refresh_devices")]internal static partial void MidiRefreshDevices();diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audio.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audio.csindex e226175d..6a811381 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audio.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Audio.cs@@ -9,7 +9,7 @@ public sealed partial class NotaEngine{// --- audio device settings (M7-1) ---- /// <summary>Re-scans connected CoreAudio devices and returns the playback-capable ones.</summary>+ /// <summary>Re-scans connected audio devices and returns the playback-capable ones.</summary>public static IReadOnlyList<AudioDevice> AudioOutputDevices(){NativeMethods.AudioRefreshDevices();@@ -22,7 +22,7 @@ public sealed partial class NotaEnginereturn list;}- /// <summary>Re-scans connected CoreAudio devices and returns the capture-capable ones.</summary>+ /// <summary>Re-scans connected audio devices and returns the capture-capable ones.</summary>public static IReadOnlyList<AudioDevice> AudioInputDevices(){NativeMethods.AudioRefreshDevices();@@ -94,6 +94,94 @@ public sealed partial class NotaEnginepublic bool AudioSilentFallback{ get { ThrowIfDisposed(); return NativeMethods.AudioSilentFallback(_handle) != 0; } }+ // --- ASIO (Windows; specs/049) ---+ // Staged like the device settings above: ApplyAudio() persists and restarts. Off Windows+ // the setters change nothing and the lists are empty.++ /// <summary>The staged audio system (WASAPI or ASIO).</summary>+ public AudioSystem AudioSystem+ { get { ThrowIfDisposed(); return NativeMethods.AudioSystem(_handle) == 1 ? AudioSystem.Asio : AudioSystem.Wasapi; } }++ /// <summary>The audio system actually running: WASAPI after a failed ASIO start fell back.</summary>+ public AudioSystem ActiveAudioSystem+ { get { ThrowIfDisposed(); return NativeMethods.AudioActiveSystem(_handle) == 1 ? AudioSystem.Asio : AudioSystem.Wasapi; } }++ /// <summary>True if this build can drive ASIO drivers (Windows).</summary>+ public bool AsioAvailable => NativeMethods.AudioAsioAvailable() != 0;++ /// <summary>Re-scans the installed ASIO drivers: Uid is the driver's CLSID, Name its+ /// display name (duplicates numbered).</summary>+ public IReadOnlyList<AudioDevice> AsioDrivers()+ {+ NativeMethods.AudioRefreshDevices();+ int n = NativeMethods.AudioAsioDriverCount();+ var list = new List<AudioDevice>(n);+ for (int i = 0; i < n; i++)+ list.Add(new AudioDevice(+ Marshal.PtrToStringUTF8(NativeMethods.AudioAsioDriverId(i)) ?? "",+ Marshal.PtrToStringUTF8(NativeMethods.AudioAsioDriverName(i)) ?? ""));+ return list;+ }++ /// <summary>Stages the audio system. Call <see cref="ApplyAudio"/> to apply.</summary>+ public void SetAudioSystem(AudioSystem system)+ { ThrowIfDisposed(); Check(NativeMethods.AudioSetSystem(_handle, (int)system)); }++ /// <summary>Stages the ASIO driver by id ("" = the first installed). Call <see cref="ApplyAudio"/>.</summary>+ public void SetAsioDriver(string id)+ { ThrowIfDisposed(); Check(NativeMethods.AudioSetAsioDriver(_handle, id ?? "")); }++ /// <summary>The staged ASIO driver id ("" = none chosen).</summary>+ public string AsioDriver+ { get { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.AudioAsioDriver(_handle)) ?? ""; } }++ /// <summary>Channel names of the open ASIO driver (empty when ASIO isn't running).</summary>+ public IReadOnlyList<string> AsioChannels(bool input)+ {+ ThrowIfDisposed();+ int flag = input ? 1 : 0;+ int n = NativeMethods.AudioAsioChannelCount(_handle, flag);+ var list = new List<string>(n);+ for (int i = 0; i < n; i++)+ list.Add(Marshal.PtrToStringUTF8(NativeMethods.AudioAsioChannelName(_handle, flag, i)) ?? $"{i + 1}");+ return list;+ }++ /// <summary>The staged first channel of the ASIO input or output pair.</summary>+ public int AsioPair(bool input)+ { ThrowIfDisposed(); return NativeMethods.AudioAsioPair(_handle, input ? 1 : 0); }++ /// <summary>Stages the ASIO pair by its first channel. Call <see cref="ApplyAudio"/>.</summary>+ public void SetAsioPair(bool input, int firstChannel)+ { ThrowIfDisposed(); Check(NativeMethods.AudioSetAsioPair(_handle, input ? 1 : 0, Math.Max(0, firstChannel))); }++ /// <summary>Opens the running ASIO driver's own settings panel; false if none runs.</summary>+ public bool OpenAsioControlPanel()+ { ThrowIfDisposed(); return NativeMethods.AudioAsioOpenControlPanel(_handle) == NativeMethods.NotaResult.Ok; }++ /// <summary>True while the ASIO driver's own settings panel is open: hold applies back.</summary>+ public bool AsioPanelOpen+ { get { ThrowIfDisposed(); return NativeMethods.AudioAsioPanelOpen(_handle) != 0; } }++ /// <summary>What the driver asked for since the last call (cleared on read).</summary>+ public AudioDeviceEvent PollDeviceEvent()+ { ThrowIfDisposed(); return (AudioDeviceEvent)NativeMethods.AudioPollDeviceEvent(_handle); }++ /// <summary>Why the last ASIO start failed and WASAPI runs instead ("" if it didn't).</summary>+ public string AudioFallbackReason+ { get { ThrowIfDisposed(); return Marshal.PtrToStringUTF8(NativeMethods.AudioFallbackReason(_handle)) ?? ""; } }++ /// <summary>The running device's input latency in frames (0 = unknown).</summary>+ public int InputLatencyFrames+ { get { ThrowIfDisposed(); return NativeMethods.AudioInputLatencyFrames(_handle); } }++ /// <summary>The running device's output latency in frames (0 = unknown).</summary>+ public int OutputLatencyFrames+ { get { ThrowIfDisposed(); return NativeMethods.AudioOutputLatencyFrames(_handle); } }++ /// <summary>Device-free ASIO self-test on a fake driver (every platform).</summary>+ public static bool AsioSelfTest() => NativeMethods.AsioSelfTest() == 1;+// --- MIDI device settings (M7-2) ---/// <summary>Re-scans connected MIDI input sources.</summary>diff --git a/src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.cs b/src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.csindex 5730759f..e0fde1db 100644--- a/src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.cs+++ b/src/managed/Nota.Presentation/ViewModels/MainWindowViewModel.cs@@ -32,6 +32,9 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable/// <summary>Version history was just turned off in Settings: the window erases the open/// project's history.</summary>public event Action? VersionHistoryTurnedOff;+ /// <summary>The audio driver restarted (or fell back) on its own, after a device event:+ /// an open Settings ▸ Audio pane re-reads the driver's buffer, latency and channels.</summary>+ public event Action? AudioDeviceRestarted;/// <summary>Turns version history on or off and persists it. Turning it off (the caller has/// confirmed) erases the open project's history; other projects lose theirs on their next save.</summary>@@ -82,6 +85,7 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposableEngineInfo = $"{Engine.SampleRate:0}\u2009Hz";_log.Info($"Engine started · {Engine.SampleRate:0}\u2009Hz");if (NoAudioOutput is { } why) { _log.Warn(why); StatusText = why; }+ else if (AsioFallbackStatus() is { } asio) { _log.Warn(asio); StatusText = asio; }Transport.Message += m => { if (m.Length > 0) StatusText = m; };@@ -107,6 +111,36 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposablePlayheadUpdated?.Invoke(Engine.PositionBeats);if (Engine.IsRecording) RecordingTick?.Invoke();ReportDropouts();+ if (_applyAfterPanel && !Engine.AsioPanelOpen) { _applyAfterPanel = false; ApplyAudioSettings(); AudioDeviceRestarted?.Invoke(); }+ PollAudioDevice();+ }++ // A settings change made while the ASIO driver's panel was open, applied once it closes.+ private bool _applyAfterPanel;++ /// <summary>The sample rate the ASIO driver refused at the last apply (0 = none).</summary>+ public double RefusedSampleRate { get; private set; }++ // The ASIO driver asked for a restart (its buffer size, rate or latencies changed in its+ // own panel) or stopped calling back (specs/049, FR-009/FR-011). Restart through the one+ // apply path — which falls back to WASAPI if the driver won't start — and carry on+ // playing from the same spot. Never restarted from inside a driver callback.+ private void PollAudioDevice()+ {+ var ev = Engine.PollDeviceEvent();+ if (ev == AudioDeviceEvent.None) return;+ bool wasPlaying = Engine.IsPlaying && !Engine.IsRecording;+ double position = Engine.PositionBeats;+ _log.Info(ev == AudioDeviceEvent.ResetRequested ? "Audio driver asked for a reset" : "Audio driver stopped responding");+ ApplyAudioSettings();+ if (ev == AudioDeviceEvent.ResetRequested && Engine.ActiveAudioSystem == AudioSystem.Asio)+ StatusText = $"Audio: driver settings changed · {Engine.NegotiatedBufferFrames} frames";+ if (wasPlaying && Engine.IsRunning)+ {+ Engine.Seek(position);+ Engine.Play();+ }+ AudioDeviceRestarted?.Invoke();}private void OnAutosaveTick()@@ -133,9 +167,20 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable/// </summary>public string ApplyAudioSettings(){+ // The driver's thread is inside its own (modal) panel: restarting now would wait on it+ // and freeze the UI. Apply when the panel closes; the tick picks it up.+ if (Engine.AsioPanelOpen)+ {+ _applyAfterPanel = true;+ RefusedSampleRate = 0; // the old refusal no longer answers this new request+ StatusText = "Close the driver's settings window to apply the change";+ return StatusText;+ }+// Don't restart the backend mid-playback.if (Engine.IsPlaying) Transport.PlayStopCommand.Execute(null);+ double askedRate = Engine.GetAudioConfig().SampleRate;SuspendEnginePolling = true;try{@@ -152,6 +197,10 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposableSuspendEnginePolling = false;}+ // The engine drops a rate the ASIO driver refused (back to device default). Remember+ // it here, so Settings can say why — also when the apply waited for the driver's panel.+ RefusedSampleRate = askedRate > 0 && Engine.ActiveAudioSystem == AudioSystem.Asio+ && Engine.GetAudioConfig().SampleRate == 0 ? askedRate : 0;EngineInfo = $"{Engine.SampleRate:0}\u2009Hz"; // the version sits beside it, as its own button (#127)int buf = Engine.NegotiatedBufferFrames;_log.Info($"Audio applied · {Engine.NegotiatedSampleRate:0}\u2009Hz · {buf} frames");@@ -161,6 +210,17 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposableStatusText = why;return StatusText;}+ if (AsioFallbackStatus() is { } asio)+ {+ _log.Warn(asio);+ StatusText = asio;+ return StatusText;+ }+ if (Engine.ActiveAudioSystem == AudioSystem.Asio)+ {+ StatusText = $"Audio: ASIO · {AsioDriverName()} · {Engine.NegotiatedSampleRate:0}\u2009Hz · {buf} frames";+ return StatusText;+ }bool fallback = Engine.AudioExclusiveFallback;if (fallback){@@ -174,6 +234,26 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposablereturn StatusText;}+ /// <summary>The ASIO driver chosen in Settings couldn't start and WASAPI runs instead+ /// (FR-011): the status line naming the driver and the reason, else null.</summary>+ public string? AsioFallbackStatus()+ {+ if (Engine.AudioSystem != AudioSystem.Asio || Engine.ActiveAudioSystem == AudioSystem.Asio) return null;+ string reason = Engine.AudioFallbackReason;+ if (reason.Length > 0) reason = char.ToUpperInvariant(reason[0]) + reason[1..] + ".";+ return $"ASIO driver ‘{AsioDriverName()}’ couldn't start — using WASAPI. {reason}".TrimEnd();+ }++ /// <summary>Display name of the staged ASIO driver (the first installed when none is staged).</summary>+ public string AsioDriverName()+ {+ var drivers = Engine.AsioDrivers();+ string id = Engine.AsioDriver;+ foreach (var d in drivers)+ if (string.Equals(d.Uid, id, StringComparison.OrdinalIgnoreCase)) return d.Name;+ return id.Length == 0 && drivers.Count > 0 ? drivers[0].Name : "ASIO";+ }+/// <summary>Why nothing is heard when no output device opened (the engine runs silently/// or not at all), else null.</summary>public string? NoAudioOutputdiff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex de712da6..d9a92f7b 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -110,6 +110,9 @@ set(NOTA_ENGINE_SOURCESsrc/audio_io/NotaConfigFile.cpp # per-user data dir + atomic file IO (all platforms)src/audio_io/ConfigJson.cpp # audio.json / midi.json via CPM nlohmann/jsonsrc/audio_io/MpeInput.cpp # MPE routing (.h/.cpp)+ src/audio_io/asio/AsioSampleFormat.cpp # ASIO core, every platform (nota_asio_selftest)+ src/audio_io/asio/AsioSession.cpp+ src/audio_io/asio/FakeAsioDriver.cppsrc/devices/Device.cpp # interface TU (vtable anchor)src/devices/Instrument.cpp # ctor + controller routingsrc/devices/MidiDevice.cpp # interface TU (vtable anchor)@@ -219,6 +222,15 @@ elseif(WIN32 OR (UNIX AND NOT APPLE))src/audio_io/desktop/GamepadInput_stub.cpp # v1: macOS-only; reports zero pads${rtmidi_SOURCE_DIR}/RtMidi.cpp)+ if(WIN32)+ # ASIO beside WASAPI (specs/049): registry list, IASIO adapter, the two facades.+ list(APPEND NOTA_ENGINE_SOURCES+ src/audio_io/windows/AsioDriverList.cpp+ src/audio_io/windows/ComAsioDriver.cpp+ src/audio_io/windows/AsioBackend.cpp+ src/audio_io/windows/AsioInput.cpp+ )+ endif()else()message(FATAL_ERROR "No Nota audio/MIDI device backend for this platform yet.")endif()@@ -280,6 +292,10 @@ elseif(WIN32)target_compile_definitions(nota_engine PRIVATE__WINDOWS_MM__ NOMINMAX WIN32_LEAN_AND_MEAN _USE_MATH_DEFINES)target_link_libraries(nota_engine PRIVATE winmm ole32)+ # ASIO (specs/049): SDK headers only, from the CPM zip (cmake/dependencies.cmake).+ target_include_directories(nota_engine SYSTEM PRIVATE ${asiosdk_SOURCE_DIR}/common)+ target_compile_definitions(nota_engine PRIVATE NOTA_HAS_ASIO=1)+ target_link_libraries(nota_engine PRIVATE advapi32 user32 avrt)elseif(UNIX AND NOT APPLE)# RtMidi -> ALSA sequencer (__LINUX_ALSA__), which links libasound directly.# miniaudio runtime-links PulseAudio/ALSA via dlopen (see nota_miniaudio.h), sodiff --git a/src/native/nota.engine/cmake/dependencies.cmake b/src/native/nota.engine/cmake/dependencies.cmakeindex c46af9d6..8c7040c4 100644--- a/src/native/nota.engine/cmake/dependencies.cmake+++ b/src/native/nota.engine/cmake/dependencies.cmake@@ -77,3 +77,14 @@ CPMAddPackage(URL "https://github.com/juce-framework/JUCE/archive/refs/tags/8.0.14.tar.gz"URL_HASH "SHA256=ceb18e4ac9ab5ea71f3f20240d5852707767a1789ab43d06656a296da9e62f3e")+# Steinberg ASIO SDK 2.3.4 (2025-10-15), used under its GPLv3 option (LICENSES/third-party.md+# note 8). Windows only, headers only: common/asio.h, iasiodrv.h, asiosys.h — no SDK .cpp+# is built (src/audio_io/windows/ talks to drivers through IASIO itself).+if(WIN32)+ CPMAddPackage(+ NAME asiosdk+ URL "https://download.steinberg.net/sdk_downloads/ASIO-SDK_2.3.4_2025-10-15.zip"+ URL_HASH "SHA256=d5ebf0c20dd2c5f43771fd0c1418f4b361bf52434ee670097cfa6b3a335e2eca"+ DOWNLOAD_ONLY YES+ )+endif()diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 01cd3c8b..9fa9e394 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -2285,11 +2285,12 @@ NOTA_API const char* nota_pluginhost_scan_path(int32_t index);/* --- audio device settings (M7-1) -----------------------------------------* The chosen output/input device (by stable UID), sample rate and buffer size- * are persisted to ~/Library/Application Support/Nota/audio.json and applied on+ * are persisted to audio.json in the data dir (nota_set_data_dir) and applied on* the next nota_audio_apply() (which restarts the audio backend). Setters only- * stage the value; nothing changes until apply. */+ * stage the value; nothing changes until apply. Devices come from CoreAudio on+ * macOS, WASAPI on Windows (plus ASIO drivers, below) and PulseAudio/ALSA on Linux. */-/* Rescan the connected CoreAudio devices (call before reading the lists). */+/* Rescan the connected devices (and installed ASIO drivers; call before reading the lists). */NOTA_API void nota_audio_refresh_devices(void);/* Number of playback- / capture-capable devices from the last refresh. */NOTA_API int32_t nota_audio_output_device_count(void);@@ -2340,6 +2341,63 @@ NOTA_API int32_t nota_audio_exclusive_fallback(const NotaEngine* engine);* (miniaudio) backend only; always 0 elsewhere. */NOTA_API int32_t nota_audio_silent_fallback(const NotaEngine* engine);+/* --- ASIO (Windows; specs/049) ---------------------------------------------+ * A second audio system beside WASAPI. Like the calls above, setters only stage;+ * nota_audio_apply() persists and restarts. On macOS/Linux every call is a no-op:+ * counts return 0, nota_audio_asio_available() returns 0, setters return NOTA_OK+ * and change nothing. If the chosen ASIO driver can't start, apply still returns+ * NOTA_OK and runs WASAPI on the system default device: nota_audio_active_system()+ * tells, nota_audio_fallback_reason() says why. */++/* Audio system: 0 = WASAPI (default), 1 = ASIO. */+NOTA_API NotaResult nota_audio_set_system(NotaEngine* engine, int32_t system);+NOTA_API int32_t nota_audio_system(const NotaEngine* engine); /* staged */+NOTA_API int32_t nota_audio_active_system(const NotaEngine* engine); /* running (after fallback) */++/* Installed ASIO drivers, refreshed by nota_audio_refresh_devices(). Strings are+ * UTF-8, owned by the engine, valid until the next refresh; NULL if out of range. */+NOTA_API int32_t nota_audio_asio_available(void); /* 1 if this build has ASIO */+NOTA_API int32_t nota_audio_asio_driver_count(void);+NOTA_API const char* nota_audio_asio_driver_id(int32_t index); /* CLSID string */+NOTA_API const char* nota_audio_asio_driver_name(int32_t index); /* display name, de-duplicated */+/* Stage the driver by id (from nota_audio_asio_driver_id). "" = the first installed. */+NOTA_API NotaResult nota_audio_set_asio_driver(NotaEngine* engine, const char* id);+NOTA_API const char* nota_audio_asio_driver(const NotaEngine* engine); /* staged id */++/* Channels of the OPEN driver (0 when ASIO is not running). Names are the driver's+ * own, UTF-8, valid until the next call. */+NOTA_API int32_t nota_audio_asio_channel_count(const NotaEngine* engine, int32_t is_input);+NOTA_API const char* nota_audio_asio_channel_name(const NotaEngine* engine, int32_t is_input, int32_t index);+/* Stage the pair by its first channel (0, 2, 4 …; a last odd channel is a mono pair). */+NOTA_API NotaResult nota_audio_set_asio_pair(NotaEngine* engine, int32_t is_input, int32_t first_channel);+NOTA_API int32_t nota_audio_asio_pair(const NotaEngine* engine, int32_t is_input); /* staged */++/* Open the running driver's own settings panel. Returns at once (NOTA_ERR_AUDIO_DEVICE+ * if no ASIO driver runs); a change there arrives as a reset-requested device event. */+NOTA_API NotaResult nota_audio_asio_open_control_panel(NotaEngine* engine);+/* 1 while that panel is open. The driver's thread is busy with it, so hold+ * nota_audio_apply() back until it closes (an apply would wait on the panel). */+NOTA_API int32_t nota_audio_asio_panel_open(const NotaEngine* engine);++/* Device events since the last call, cleared on read: 0 none, 1 reset requested+ * (the driver changed its buffer size / rate / latencies: re-apply), 2 driver failed+ * (stopped calling back: re-apply, which falls back to WASAPI). Poll from the UI tick. */+NOTA_API int32_t nota_audio_poll_device_event(NotaEngine* engine);+/* Why the last ASIO start failed (human reason, UTF-8, engine-owned), "" if it didn't. */+NOTA_API const char* nota_audio_fallback_reason(const NotaEngine* engine);++/* Device latencies of the running backend in frames, as the driver reports them+ * (0 if unknown — every non-ASIO backend). Recorded takes are moved earlier by+ * input + output. */+NOTA_API int32_t nota_audio_input_latency_frames(const NotaEngine* engine);+NOTA_API int32_t nota_audio_output_latency_frames(const NotaEngine* engine);++/* Device-free ASIO self-test on a fake driver: sample formats, pair routing and+ * silence, duplex order, resets, failures, latency compensation, audio.json keys.+ * Returns 1 if every case passes, else 0 (the failing case is printed to stderr).+ * Runs on every platform. */+NOTA_API int32_t nota_asio_selftest(void);+/* --- MIDI device settings (M7-2) ------------------------------------------* Which CoreMIDI inputs the engine listens to. The chosen set is persisted as a* blocklist of disabled uids in ~/Library/Application Support/Nota/midi.jsondiff --git a/src/native/nota.engine/src/abi/nota_engine_audio.cpp b/src/native/nota.engine/src/abi/nota_engine_audio.cppindex 7e58ae51..1d506220 100644--- a/src/native/nota.engine/src/abi/nota_engine_audio.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_audio.cpp@@ -7,14 +7,27 @@#include "nota_engine_internal.h"+#include "audio_io/AudioBackendFactory.h"#include "audio_io/AudioConfig.h"#include "audio_io/MidiConfig.h"#include "audio_io/MpeInput.h"+#include "audio_io/NotaConfigFile.h"+#include "audio_io/asio/AsioSession.h"+#include "audio_io/asio/FakeAsioDriver.h"+#ifdef NOTA_HAS_ASIO+#include "audio_io/windows/AsioBackend.h"+#include "audio_io/windows/AsioDriverList.h"+#endif#include <algorithm>+#include <atomic>+#include <chrono>#include <cmath>-+#include <cstdio>+#include <filesystem>+#include <memory>#include <string>+#include <thread>#include <vector>// ---- Audio device settings (M7-1) -----------------------------------------@@ -29,6 +42,10 @@ const char* deviceField(const std::vector<nota::AudioDeviceInfo>& list, int32_tif (i < 0 || i >= static_cast<int32_t>(list.size())) return nullptr;return uid ? list[i].uid.c_str() : list[i].name.c_str();}+#ifdef NOTA_HAS_ASIO+// Installed ASIO drivers, refreshed with the device lists (specs/049).+std::vector<nota::asio::AsioDriverInfo> g_asioDrivers;+#endif} // namespaceextern "C" {@@ -36,6 +53,9 @@ extern "C" {void nota_audio_refresh_devices(void) {g_outputDevices = nota::enumerateAudioDevices(/*inputScope=*/false);g_inputDevices = nota::enumerateAudioDevices(/*inputScope=*/true);+#ifdef NOTA_HAS_ASIO+ g_asioDrivers = nota::asio::enumerateAsioDrivers();+#endif}int32_t nota_audio_output_device_count(void) {@@ -121,8 +141,489 @@ int32_t nota_audio_silent_fallback(const NotaEngine* e) {return (e && CENG(e)->audioSilentFallback()) ? 1 : 0;}+// ---- ASIO (Windows; specs/049) ---------------------------------------------++NotaResult nota_audio_set_system(NotaEngine* e, int32_t system) {+ if (!e) return NOTA_ERR_INVALID_ARG;+ ENG(e)->setAudioSystem(system == 1 ? nota::AudioSystem::Asio : nota::AudioSystem::Wasapi);+ return NOTA_OK;+}+int32_t nota_audio_system(const NotaEngine* e) {+ return (e && CENG(e)->audioConfig().audioSystem == nota::AudioSystem::Asio) ? 1 : 0;+}+int32_t nota_audio_active_system(const NotaEngine* e) {+ return (e && CENG(e)->activeAudioSystem() == nota::AudioSystem::Asio) ? 1 : 0;+}++int32_t nota_audio_asio_available(void) {+ return nota::asioSupported() ? 1 : 0;+}+int32_t nota_audio_asio_driver_count(void) {+#ifdef NOTA_HAS_ASIO+ return static_cast<int32_t>(g_asioDrivers.size());+#else+ return 0;+#endif+}+const char* nota_audio_asio_driver_id(int32_t i) {+#ifdef NOTA_HAS_ASIO+ if (i >= 0 && i < static_cast<int32_t>(g_asioDrivers.size())) return g_asioDrivers[i].clsid.c_str();+#else+ (void)i;+#endif+ return nullptr;+}+const char* nota_audio_asio_driver_name(int32_t i) {+#ifdef NOTA_HAS_ASIO+ if (i >= 0 && i < static_cast<int32_t>(g_asioDrivers.size())) return g_asioDrivers[i].displayName.c_str();+#else+ (void)i;+#endif+ return nullptr;+}+NotaResult nota_audio_set_asio_driver(NotaEngine* e, const char* id) {+ if (!e) return NOTA_ERR_INVALID_ARG;+#ifdef NOTA_HAS_ASIO+ const std::string clsid = id ? id : "";+ if (g_asioDrivers.empty()) g_asioDrivers = nota::asio::enumerateAsioDrivers();+ // The registry name travels with the CLSID: it finds the driver again if a reinstall+ // gives it a new CLSID (research R10).+ const auto* d = clsid.empty() ? nullptr : nota::asio::findAsioDriver(g_asioDrivers, clsid, {});+ ENG(e)->setAsioDriver(clsid, d ? d->name : std::string{});+#else+ (void)id;+#endif+ return NOTA_OK;+}+const char* nota_audio_asio_driver(const NotaEngine* e) {+ static std::string s; // owned by the engine, valid until the next call+ s = e ? CENG(e)->audioConfig().asioDriverClsid : std::string{};+ return s.c_str();+}++int32_t nota_audio_asio_channel_count(const NotaEngine* e, int32_t is_input) {+#ifdef NOTA_HAS_ASIO+ if (e && CENG(e)->activeAudioSystem() == nota::AudioSystem::Asio)+ return static_cast<int32_t>(nota::asio::sharedAsioSession().channels(is_input != 0).size());+#else+ (void)e;+ (void)is_input;+#endif+ return 0;+}+const char* nota_audio_asio_channel_name(const NotaEngine* e, int32_t is_input, int32_t index) {+#ifdef NOTA_HAS_ASIO+ static std::string s; // valid until the next call+ if (e && CENG(e)->activeAudioSystem() == nota::AudioSystem::Asio) {+ const auto& ch = nota::asio::sharedAsioSession().channels(is_input != 0);+ if (index >= 0 && index < static_cast<int32_t>(ch.size())) {+ s = ch[static_cast<size_t>(index)].name;+ return s.c_str();+ }+ }+#else+ (void)e;+ (void)is_input;+ (void)index;+#endif+ return nullptr;+}+NotaResult nota_audio_set_asio_pair(NotaEngine* e, int32_t is_input, int32_t first_channel) {+ if (!e || first_channel < 0) return NOTA_ERR_INVALID_ARG;+ ENG(e)->setAsioPair(is_input != 0, first_channel);+ return NOTA_OK;+}+int32_t nota_audio_asio_pair(const NotaEngine* e, int32_t is_input) {+ if (!e) return 0;+ return is_input ? CENG(e)->audioConfig().asioInputPair : CENG(e)->audioConfig().asioOutputPair;+}++NotaResult nota_audio_asio_open_control_panel(NotaEngine* e) {+ if (!e) return NOTA_ERR_INVALID_ARG;+#ifdef NOTA_HAS_ASIO+ if (CENG(e)->activeAudioSystem() == nota::AudioSystem::Asio && nota::asio::sharedAsioSession().openControlPanel())+ return NOTA_OK;+#endif+ return NOTA_ERR_AUDIO_DEVICE;+}++int32_t nota_audio_asio_panel_open(const NotaEngine* e) {+#ifdef NOTA_HAS_ASIO+ if (e && CENG(e)->activeAudioSystem() == nota::AudioSystem::Asio && nota::asio::sharedAsioSession().panelOpen())+ return 1;+#else+ (void)e;+#endif+ return 0;+}++int32_t nota_audio_poll_device_event(NotaEngine* e) {+ return e ? ENG(e)->pollAudioDeviceEvent() : 0;+}+const char* nota_audio_fallback_reason(const NotaEngine* e) {+ static std::string s; // owned by the engine, valid until the next call+ s = e ? CENG(e)->audioFallbackReason() : std::string{};+ return s.c_str();+}++int32_t nota_audio_input_latency_frames(const NotaEngine* e) {+ return e ? CENG(e)->audioInputLatencyFrames() : 0;+}+int32_t nota_audio_output_latency_frames(const NotaEngine* e) {+ return e ? CENG(e)->audioOutputLatencyFrames() : 0;+}+} // extern "C"+// ---- ASIO self-test (specs/049, FR-016) -------------------------------------+// Drives AsioSession through FakeAsioDriver on the calling thread. Uses the ASIO callback+// routing of a session of its own, so it must not run while a real ASIO driver is open+// (the smoke test never starts the audio backend).++namespace {++using nota::asio::AsioSession;+using nota::asio::FakeAsioDriver;+using nota::asio::SampleType;++struct AsioCheck {+ bool ok = true;+ void operator()(bool cond, const char* what) {+ if (cond) return;+ ok = false;+ std::fprintf(stderr, "nota_asio_selftest: FAILED %s\n", what);+ }+};++double lsb(SampleType t) {+ switch (t) {+ case SampleType::Int16LSB:+ case SampleType::Int32LSB16: return 1.0 / 32768.0;+ case SampleType::Int32LSB18: return 1.0 / 131072.0;+ case SampleType::Int32LSB20: return 1.0 / 524288.0;+ case SampleType::Int24LSB:+ case SampleType::Int32LSB24: return 1.0 / 8388608.0;+ case SampleType::Int32LSB: return 1.0 / 2147483648.0;+ default: return 0.0;+ }+}++// A session opened on a fresh fake driver; `fake` stays usable while the session owns it.+struct Rig {+ AsioSession session;+ FakeAsioDriver* fake = nullptr;+ bool open(FakeAsioDriver::Config cfg, AsioSession::Options opt = {},+ void (*tweak)(FakeAsioDriver&) = nullptr) {+ auto d = std::make_unique<FakeAsioDriver>(std::move(cfg));+ fake = d.get();+ if (tweak) tweak(*d);+ return session.open(std::move(d), opt);+ }+};++void checkFormats(AsioCheck& check) {+ const SampleType types[] = {SampleType::Int16LSB, SampleType::Int24LSB, SampleType::Int32LSB,+ SampleType::Float32LSB, SampleType::Float64LSB, SampleType::Int32LSB16,+ SampleType::Int32LSB18, SampleType::Int32LSB20, SampleType::Int32LSB24};+ std::vector<float> src{-1.0f, -0.5f, 0.0f, 0.5f, 1.0f};+ for (int i = 0; i < 64; ++i) src.push_back(0.8f * static_cast<float>(std::sin(i * 0.37)));+ const auto n = static_cast<int32_t>(src.size());+ for (SampleType t : types) {+ check(nota::asio::isSupported(t), "every LSB PCM / float type is supported");+ std::vector<uint8_t> raw(static_cast<size_t>(n) * 8);+ std::vector<float> back(static_cast<size_t>(n) * 2, 7.0f);+ nota::asio::fromFloat(src.data(), 1, t, raw.data(), n);+ nota::asio::toFloat(raw.data(), t, back.data(), n, 2); // stride 2: every other float+ bool within = true;+ for (int32_t i = 0; i < n; ++i)+ if (std::fabs(back[static_cast<size_t>(i) * 2] - src[static_cast<size_t>(i)]) > lsb(t) * 1.01 + 1e-7)+ within = false;+ check(within, nota::asio::sampleTypeName(t)); // round trip within 1 LSB+ check(back[1] == 7.0f, "toFloat honours the stride");+ }+ for (SampleType t : {SampleType::Int16MSB, SampleType::Int24MSB, SampleType::Int32MSB, SampleType::Float32MSB,+ SampleType::Float64MSB, SampleType::Int32MSB16, SampleType::Int32MSB24,+ SampleType::DSDInt8LSB1, SampleType::DSDInt8MSB1, SampleType::DSDInt8NER8})+ check(!nota::asio::isSupported(t), "MSB and DSD types are refused");+}++void checkRouting(AsioCheck& check) {+ // Output pair 2 of an 8-out driver gets the render; every other output stays exactly zero.+ for (SampleType t : {SampleType::Int32LSB, SampleType::Float32LSB}) {+ Rig rig;+ FakeAsioDriver::Config cfg;+ cfg.inputs = 0;+ cfg.outputs = 8;+ cfg.outputType = t;+ AsioSession::Options opt;+ opt.outputPair = 2;+ check(rig.open(cfg, opt), "8-out fake opens");+ rig.session.setRenderCallback([](float* out, int32_t n) {+ for (int32_t i = 0; i < n; ++i) {+ out[i * 2] = 0.25f;+ out[i * 2 + 1] = -0.5f;+ }+ });+ check(rig.session.start(), "8-out fake starts");+ rig.fake->pump(100);+ const auto& l = rig.fake->written(2);+ const auto& r = rig.fake->written(3);+ bool pair = l.size() == 100u * 64u && r.size() == l.size();+ for (size_t i = 0; pair && i < l.size(); ++i)+ pair = std::fabs(l[i] - 0.25f) <= lsb(t) && std::fabs(r[i] + 0.5f) <= lsb(t);+ check(pair, t == SampleType::Int32LSB ? "Int32LSB render on outputs 3/4" : "Float32LSB render on outputs 3/4");+ bool silent = true;+ for (int32_t ch : {0, 1, 4, 5, 6, 7}) silent = silent && !rig.fake->nonZeroBytes(ch);+ check(silent, "every other output is exact zeros each switch");+ check(rig.fake->outputReadyCalls() == 100, "outputReady after every switch");+ rig.session.close();+ }+ // A one-output driver plays the mono down-sum.+ Rig mono;+ FakeAsioDriver::Config cfg;+ cfg.inputs = 0;+ cfg.outputs = 1;+ check(mono.open(cfg), "1-out fake opens");+ mono.session.setRenderCallback([](float* out, int32_t n) {+ for (int32_t i = 0; i < n; ++i) {+ out[i * 2] = 0.2f;+ out[i * 2 + 1] = 0.6f;+ }+ });+ mono.session.start();+ mono.fake->pump(4);+ const auto& m = mono.fake->written(0);+ check(!m.empty() && std::fabs(m.front() - 0.4f) < 1e-6f && std::fabs(m.back() - 0.4f) < 1e-6f,+ "mono output is the down-sum");+ // An out-of-range pair falls back to the first.+ Rig clamp;+ cfg.outputs = 2;+ AsioSession::Options far;+ far.outputPair = 6;+ check(clamp.open(cfg, far) && clamp.session.outputPair() == 0, "out-of-range pair clamps to the first");+}++void checkDuplex(AsioCheck& check) {+ // Input pair 2 of a 4-in driver reaches the input callback, before render, every switch.+ Rig rig;+ FakeAsioDriver::Config cfg;+ cfg.inputs = 4;+ cfg.outputs = 2;+ cfg.inputType = SampleType::Int24LSB;+ cfg.inputSignal = [](int32_t ch, int64_t) { return 0.1f * static_cast<float>(ch + 1); };+ AsioSession::Options opt;+ opt.inputPair = 2;+ check(rig.open(cfg, opt), "duplex fake opens");+ std::vector<char> order;+ float gotL = 0.0f, gotR = 0.0f;+ const nota::InputCallback in = [&](const float* s, int32_t) {+ order.push_back('i');+ gotL = s[0];+ gotR = s[1];+ };+ rig.session.setRenderCallback([&](float*, int32_t) { order.push_back('r'); });+ rig.session.setInputCallback(&in);+ rig.session.start();+ rig.fake->pump(3);+ check(order == std::vector<char>{'i', 'r', 'i', 'r', 'i', 'r'}, "input of switch n before render of switch n");+ check(std::fabs(gotL - 0.3f) < 1e-6f && std::fabs(gotR - 0.4f) < 1e-6f, "input pair 3/4 reaches the callback");+ rig.session.setInputCallback(nullptr);+ rig.fake->pump(1);+ check(order.size() == 7, "an unregistered input is no longer called");+ rig.session.close();++ // A trailing odd input is a mono pair: duplicated to both sides.+ Rig mono;+ cfg.inputs = 3;+ check(mono.open(cfg, opt), "3-in fake opens");+ mono.session.setInputCallback(&in);+ mono.session.start();+ mono.fake->pump(1);+ check(std::fabs(gotL - 0.3f) < 1e-6f && std::fabs(gotR - 0.3f) < 1e-6f, "mono input is duplicated");+ mono.session.setInputCallback(nullptr);+ mono.session.close();++ // Latency compensation: in 100 + out 150 frames moves a take 250 frames earlier.+ Rig lat;+ cfg.inputLatency = 100;+ cfg.outputLatency = 150;+ check(lat.open(cfg), "latency fake opens");+ const int32_t roundTrip = lat.session.inputLatency() + lat.session.outputLatency();+ check(roundTrip == 250, "driver latencies are reported");+ const double spb = 24000.0; // 120 BPM at 48 kHz+ double trim = -1.0;+ const double start = nota::Engine::latencyCompensatedStart(8.0, roundTrip, spb, &trim);+ check(std::fabs((8.0 - start) * spb - 250.0) < 1e-6 && trim == 0.0, "take starts 250 frames earlier");+ const double early = nota::Engine::latencyCompensatedStart(100.0 / spb, roundTrip, spb, &trim);+ check(early == 0.0 && std::fabs(trim - 150.0) < 1e-6, "a take at the very start trims instead");+ check(nota::Engine::latencyCompensatedStart(8.0, 0, spb, &trim) == 8.0, "no latency, no shift");+}++void checkResets(AsioCheck& check) {+ Rig rig;+ FakeAsioDriver::Config cfg;+ AsioSession::Options opt;+ opt.sampleRate = 96000.0; // the fake supports 44.1 / 48 kHz only+ check(rig.open(cfg, opt), "fake opens with an unsupported rate request");+ check(rig.session.sampleRateRefused() && rig.session.sampleRate() == 48000.0,+ "an unsupported rate is refused and the driver's rate kept");+ rig.session.start();+ for (int32_t sel : {nota::asio::kResetRequest, nota::asio::kBufferSizeChange, nota::asio::kLatenciesChanged}) {+ check(rig.fake->sendMessage(sel) == 1, "reset-type message accepted");+ check(rig.session.pollEvent() == AsioSession::kEventResetRequested, "reset message -> one RESET_REQUESTED");+ check(rig.session.pollEvent() == AsioSession::kEventNone, "the event is cleared on read");+ }+ rig.fake->changeSampleRate(44100.0);+ check(rig.session.pollEvent() == AsioSession::kEventResetRequested, "sampleRateDidChange -> RESET_REQUESTED");+ check(rig.session.driverChangedRate() == 44100.0, "a rate set in the driver's panel is reported with the reset");+ check(rig.session.pollEvent() == AsioSession::kEventNone, "rate event cleared on read");+ rig.fake->pump(3);+ check(rig.session.pollEvent() == AsioSession::kEventNone, "steady positions raise nothing");+ rig.fake->setPositionStep(64 + 37);+ rig.fake->pump(2);+ check(rig.session.pollEvent() == AsioSession::kEventResetRequested, "silent buffer-size change -> RESET_REQUESTED");+ check(rig.session.pollEvent() == AsioSession::kEventNone, "buffer-size event cleared on read");++ // A reset sent while the driver's panel is open waits for the panel to close — and so+ // does the watchdog: restarting now would queue behind the modal panel.+ // The driver may also stop its buffers while its panel reconfigures it: once the panel+ // closes, the pending reset wins over the watchdog (reopen ASIO, don't fall back).+ rig.fake->setPositionStep(0);+ rig.session.setWatchdogTimeout(std::chrono::milliseconds(30));+ rig.fake->setPanelOpen(true);+ rig.fake->sendMessage(nota::asio::kResetRequest);+ std::this_thread::sleep_for(std::chrono::milliseconds(60));+ check(rig.session.pollEvent() == AsioSession::kEventNone, "no restart while the driver's panel is open");+ std::this_thread::sleep_for(std::chrono::milliseconds(60)); // silent past the watchdog, panel still open+ rig.fake->setPanelOpen(false);+ check(rig.session.pollEvent() == AsioSession::kEventResetRequested,+ "after the panel closes the deferred reset comes first, not DRIVER_FAILED");++ int xruns = 0;+ Rig ov;+ check(ov.open(FakeAsioDriver::Config{}), "overload fake opens");+ ov.session.setXrunCallback([&] { ++xruns; });+ ov.session.start();+ ov.fake->sendMessage(nota::asio::kOverload);+ check(xruns == 1, "kAsioOverload counts a dropout");+ check(ov.fake->sendMessage(nota::asio::kSelectorSupported, nota::asio::kResetRequest) == 1 &&+ ov.fake->sendMessage(nota::asio::kEngineVersion) == 2 &&+ ov.fake->sendMessage(nota::asio::kSupportsTimeInfo) == 1,+ "host answers the selector queries");+}++void checkFailures(AsioCheck& check) {+ Rig busy;+ FakeAsioDriver::Config cfg;+ cfg.initFails = true;+ check(!busy.open(cfg) && busy.session.failure() == AsioSession::Failure::InitFailed &&+ !busy.session.failureText().empty() && busy.session.state() == AsioSession::State::Failed,+ "init fails -> Failed(InitFailed) with a reason");++ Rig msb;+ check(!msb.open(FakeAsioDriver::Config{}, {}, [](FakeAsioDriver& d) { d.setOutputType(1, SampleType::Int32MSB); }) &&+ msb.session.failure() == AsioSession::Failure::UnsupportedFormat,+ "MSB output -> Failed(UnsupportedFormat)");++ Rig none;+ FakeAsioDriver::Config noOut;+ noOut.outputs = 0;+ check(!none.open(noOut) && none.session.failure() == AsioSession::Failure::NoOutputs, "no outputs -> Failed(NoOutputs)");++ Rig silent;+ check(silent.open(FakeAsioDriver::Config{}), "watchdog fake opens");+ silent.session.setWatchdogTimeout(std::chrono::milliseconds(60));+ silent.session.start();+ silent.fake->pump(2);+ check(silent.session.pollEvent() == AsioSession::kEventNone, "a driver calling back is healthy");+ silent.fake->setStopsCallingBack(true);+ std::this_thread::sleep_for(std::chrono::milliseconds(150));+ check(silent.session.pollEvent() == AsioSession::kEventDriverFailed &&+ silent.session.failure() == AsioSession::Failure::Stopped,+ "a driver that stops calling back -> DRIVER_FAILED");+ silent.session.close();++ Rig late;+ int renders = 0;+ check(late.open(FakeAsioDriver::Config{}), "late-callback fake opens");+ late.session.setRenderCallback([&](float*, int32_t) { ++renders; });+ late.session.start();+ late.fake->pump(2);+ late.session.stop();+ late.fake->pump(1, /*evenIfStopped=*/true);+ check(renders == 2, "a bufferSwitch after stop() is ignored");++ // A switch that never returns (a stalled plug-in): teardown must not free what it reads,+ // and no driver may open next to it. Here the "stall" ends after teardown gave up.+ AsioSession stuck;+ auto drv = std::make_unique<FakeAsioDriver>(FakeAsioDriver::Config{});+ FakeAsioDriver* fake = drv.get(); // leaked with the session's state when it wedges+ check(stuck.open(std::move(drv), {}), "stall fake opens");+ std::atomic<bool> inRender{false}, release{false};+ stuck.setRenderCallback([&](float* out, int32_t n) {+ inRender = true;+ while (!release.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1));+ std::fill(out, out + static_cast<size_t>(n) * 2, 0.5f);+ });+ stuck.start();+ std::thread audio([fake] { fake->pump(1); });+ while (!inRender.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1));+ stuck.close(); // gives up after its bounded wait and leaks the switch's state+ check(stuck.wedged(), "a switch that never returns wedges the session");+ release = true;+ audio.join(); // the switch finishes on memory that is still alive+ check(!fake->written(0).empty() && fake->written(0).front() == 0.5f, "the stalled switch completes safely");+ check(!stuck.open(std::make_unique<FakeAsioDriver>(FakeAsioDriver::Config{}), {}) &&+ stuck.failure() == AsioSession::Failure::Timeout,+ "no driver opens next to a wedged switch");+}++void checkConfigKeys(AsioCheck& check) {+ namespace fs = std::filesystem;+ const std::string saved = nota::cfgfile::dataDirOverride();+ std::error_code ec;+ const fs::path dir = fs::temp_directory_path(ec) /+ ("nota-asio-selftest-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+ nota::cfgfile::setDataDirOverride(dir.string());+ nota::AudioConfig cfg;+ check(nota::loadAudioConfig().audioSystem == nota::AudioSystem::Wasapi, "missing audio.json keys mean WASAPI");+ cfg.audioSystem = nota::AudioSystem::Asio;+ cfg.asioDriverClsid = "{11111111-2222-3333-4444-555555555555}";+ cfg.asioDriverName = "Fake ASIO";+ cfg.asioOutputPair = 4;+ cfg.asioInputPair = 2;+ nota::saveAudioConfig(cfg);+ const nota::AudioConfig back = nota::loadAudioConfig();+ check(back.asioDriverClsid == cfg.asioDriverClsid && back.asioDriverName == cfg.asioDriverName &&+ back.asioOutputPair == 4 && back.asioInputPair == 2,+ "ASIO keys round-trip through audio.json");+#if defined(_WIN32)+ check(back.audioSystem == nota::AudioSystem::Asio, "audioSystem round-trips on Windows");+#else+ check(back.audioSystem == nota::AudioSystem::Wasapi, "audioSystem reads as the native system off Windows");+#endif+ nota::cfgfile::setDataDirOverride(saved);+ fs::remove_all(dir, ec);+}++} // namespace++extern "C" int32_t nota_asio_selftest(void) {+ AsioCheck check;+ {+ // On the heap: an Engine is far bigger than a 1 MB Windows main-thread stack.+ auto engine = std::make_unique<nota::Engine>();+ check(engine->monitorSharedClockSelfTest(), "an ASIO block split by a loop reaches monitoring whole");+ }+ checkFormats(check);+ checkRouting(check);+ checkDuplex(check);+ checkResets(check);+ checkFailures(check);+ checkConfigKeys(check);+ return check.ok ? 1 : 0;+}+// ---- MIDI device settings (M7-2) ------------------------------------------namespace {diff --git a/src/native/nota.engine/src/audio_io/AudioBackend.h b/src/native/nota.engine/src/audio_io/AudioBackend.hindex 95275514..b04eda8c 100644--- a/src/native/nota.engine/src/audio_io/AudioBackend.h+++ b/src/native/nota.engine/src/audio_io/AudioBackend.h@@ -3,14 +3,16 @@//// Audio device backend abstraction.//-// M0 ships a CoreAudio implementation. The engine talks only to this interface-// so the device layer stays swappable (e.g. a future JUCE-based backend for the-// Windows/Linux ports, or JUCE for plugin hosting). See ARCHITECTURE.md § Audio engine.+// Implementations: CoreAudio (macOS), miniaudio (WASAPI on Windows, PulseAudio/ALSA on+// Linux) and ASIO (Windows, audio_io/windows/AsioBackend over a shared AsioSession). The+// engine talks only to this interface — AudioBackendFactory picks the implementation — so+// the device layer stays swappable. See ARCHITECTURE.md § Audio engine.#pragma once#include <cstdint>#include <functional>+#include <string>namespace nota {@@ -21,8 +23,8 @@ using RenderCallback = std::function<void(float* out, int32_t numFrames)>;// Requested device configuration (M7-1). Zero fields mean "use the device// default": device 0 = system default output, sampleRate 0 / bufferFrames 0 =-// whatever the device is already set to. `device` is a CoreAudio AudioDeviceID-// carried as a plain integer so this header stays free of CoreAudio types.+// whatever the device is already set to. `device` is a backend-specific device+// handle carried as a plain integer so this header stays free of platform types.//// `wasapiExclusive` (Windows/WASAPI only; ignored on other platforms) asks// miniaudio to open the device in exclusive mode. The backend MUST fall back to@@ -33,6 +35,12 @@ struct BackendConfig {double sampleRate = 0.0;int32_t bufferFrames = 0;bool wasapiExclusive = false;+ // ASIO (Windows; specs/049): the driver by CLSID, else by registry name, and the first+ // channel of each pair. bufferFrames is ignored under ASIO — the driver decides.+ std::string asioDriverClsid;+ std::string asioDriverName;+ int32_t asioOutputPair = 0;+ int32_t asioInputPair = 0;};class AudioBackend {@@ -70,6 +78,30 @@ class AudioBackend {virtual void setXrunCallback(std::function<void()> cb) { (void)cb; }virtual bool isRunning() const = 0;++ // Device latencies in frames as the driver reports them (specs/049, research R7): the+ // engine compensates recorded takes by input + output. 0 = unknown (CoreAudio, miniaudio).+ virtual int32_t inputLatencyFrames() const { return 0; }+ virtual int32_t outputLatencyFrames() const { return 0; }++ // True when capture comes from the same callback and clock as output (ASIO duplex):+ // input for block n is queued before block n renders, so monitoring needs no cushion (R8).+ virtual bool sharesInputClock() const { return false; }++ // Device event since the last call, cleared on read (NotaAudioDeviceEvent: 0 none,+ // 1 reset requested, 2 driver failed). Polled from the UI thread.+ virtual int32_t pollDeviceEvent() { return 0; }++ // Why the last start() failed, or why the running device failed (a DRIVER_FAILED event),+ // for the fallback message ("" if neither).+ virtual const char* fallbackReason() const { return ""; }++ // True if the last start() asked for a sample rate the device refused and kept its own.+ virtual bool sampleRateRefused() const { return false; }++ // After a reset-requested event: the rate the user picked in the device's own settings+ // (0 = unchanged). The engine then stops requesting its saved rate, so a reopen keeps it.+ virtual double deviceChangedRate() const { return 0.0; }};} // namespace notadiff --git a/src/native/nota.engine/src/audio_io/AudioBackendFactory.cpp b/src/native/nota.engine/src/audio_io/AudioBackendFactory.cppindex f28883a0..53d94f0f 100644--- a/src/native/nota.engine/src/audio_io/AudioBackendFactory.cpp+++ b/src/native/nota.engine/src/audio_io/AudioBackendFactory.cpp@@ -14,10 +14,19 @@#else#error "No audio backend for this platform yet (see AudioBackendFactory.cpp)."#endif+#ifdef NOTA_HAS_ASIO+#include "audio_io/windows/AsioBackend.h"+#include "audio_io/windows/AsioInput.h"+#endifnamespace nota {-std::unique_ptr<AudioBackend> createAudioBackend() {+std::unique_ptr<AudioBackend> createAudioBackend(AudioSystem system) {+#ifdef NOTA_HAS_ASIO+ if (system == AudioSystem::Asio) return std::make_unique<AsioBackend>();+#else+ (void)system;+#endif#if defined(__APPLE__)return std::make_unique<CoreAudioBackend>();#else@@ -25,7 +34,12 @@ std::unique_ptr<AudioBackend> createAudioBackend() {#endif}-std::unique_ptr<AudioInput> createAudioInput() {+std::unique_ptr<AudioInput> createAudioInput(AudioSystem system) {+#ifdef NOTA_HAS_ASIO+ if (system == AudioSystem::Asio) return std::make_unique<AsioInput>();+#else+ (void)system;+#endif#if defined(__APPLE__)return std::make_unique<CoreAudioInput>();#else@@ -33,4 +47,12 @@ std::unique_ptr<AudioInput> createAudioInput() {#endif}+bool asioSupported() {+#ifdef NOTA_HAS_ASIO+ return true;+#else+ return false;+#endif+}+} // namespace notadiff --git a/src/native/nota.engine/src/audio_io/AudioBackendFactory.h b/src/native/nota.engine/src/audio_io/AudioBackendFactory.hindex e630571c..553c053e 100644--- a/src/native/nota.engine/src/audio_io/AudioBackendFactory.h+++ b/src/native/nota.engine/src/audio_io/AudioBackendFactory.h@@ -2,20 +2,28 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// Platform-selected construction of the audio output backend and input capture.-// macOS -> CoreAudio (HAL); Windows -> miniaudio (WASAPI). The engine never-// names a concrete backend; it asks the factory, so the device layer stays-// swappable per platform (ARCHITECTURE.md § Audio engine).+// macOS -> CoreAudio (HAL); Windows -> miniaudio (WASAPI) or ASIO (specs/049); Linux ->+// miniaudio. The engine never names a concrete backend; it asks the factory, so the device+// layer stays swappable per platform (ARCHITECTURE.md § Audio engine). The ASIO backend and+// input share one process-wide AsioSession; only this factory knows.#pragma once#include "AudioBackend.h"+#include "AudioConfig.h"#include "AudioInput.h"#include <memory>namespace nota {-std::unique_ptr<AudioBackend> createAudioBackend();-std::unique_ptr<AudioInput> createAudioInput();+// `system` is honoured on Windows builds with ASIO; elsewhere it is ignored.+std::unique_ptr<AudioBackend> createAudioBackend(AudioSystem system = AudioSystem::Wasapi);+// Pass the system that is actually running (after any fallback), so ASIO capture binds to+// the open driver instead of opening a second device.+std::unique_ptr<AudioInput> createAudioInput(AudioSystem system = AudioSystem::Wasapi);++// True if this build can drive ASIO drivers (Windows).+bool asioSupported();} // namespace notadiff --git a/src/native/nota.engine/src/audio_io/AudioConfig.h b/src/native/nota.engine/src/audio_io/AudioConfig.hindex 1f1a48c1..4f7a375a 100644--- a/src/native/nota.engine/src/audio_io/AudioConfig.h+++ b/src/native/nota.engine/src/audio_io/AudioConfig.h@@ -2,10 +2,12 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// Audio device configuration (M7-1): the user's chosen output/input device,-// sample rate and buffer size, persisted across launches, plus CoreAudio-// device enumeration. Devices are keyed by their stable UID string-// (kAudioDevicePropertyDeviceUID) — the numeric AudioDeviceID is not stable-// across reboots/reconnects, so we resolve UID -> id at start() time.+// sample rate and buffer size, persisted across launches, plus device+// enumeration (CoreAudio on macOS, miniaudio on Windows/Linux). Devices are keyed+// by a stable UID string — numeric device ids are not stable across+// reboots/reconnects, so we resolve UID -> id at start() time. On Windows the+// config also picks the audio system (WASAPI or ASIO) and the ASIO driver and+// channel pairs (specs/049).#pragma once@@ -15,12 +17,20 @@namespace nota {+// Windows audio system (specs/049). Elsewhere always Wasapi, meaning "the native backend".+enum class AudioSystem : int32_t { Wasapi = 0, Asio = 1 };+struct AudioConfig {std::string outputDeviceUid; // "" = system default outputstd::string inputDeviceUid; // "" = system default inputdouble sampleRate = 0.0; // 0 = device default- int32_t bufferFrames = 0; // 0 = device default+ int32_t bufferFrames = 0; // 0 = device default (ignored under ASIO: the driver decides)bool wasapiExclusive = false; // Windows/WASAPI only; ignored elsewhere+ AudioSystem audioSystem = AudioSystem::Wasapi;+ std::string asioDriverClsid; // the chosen ASIO driver's CLSID (primary key)+ std::string asioDriverName; // its registry name (fallback key if the CLSID changed)+ int32_t asioOutputPair = 0; // first channel of the output pair+ int32_t asioInputPair = 0; // first channel of the input pair};struct AudioDeviceInfo {@@ -37,7 +47,7 @@ std::vector<AudioDeviceInfo> enumerateAudioDevices(bool inputScope);// UID falls back to the current system default device; 0 if none exists.uint32_t resolveAudioDeviceId(const std::string& uid, bool inputScope);-// Persistence: ~/Library/Application Support/Nota/audio.json (atomic write).+// Persistence: audio.json in the data dir the app sets (nota_set_data_dir), atomic write.AudioConfig loadAudioConfig();void saveAudioConfig(const AudioConfig& cfg);diff --git a/src/native/nota.engine/src/audio_io/AudioInput.h b/src/native/nota.engine/src/audio_io/AudioInput.hindex c36dc865..860f8881 100644--- a/src/native/nota.engine/src/audio_io/AudioInput.h+++ b/src/native/nota.engine/src/audio_io/AudioInput.h@@ -2,9 +2,10 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// Audio input capture abstraction. macOS ships a CoreAudio (HAL) implementation-// (CoreAudioInput); the Windows port ships a miniaudio/WASAPI one. The engine-// talks only to this interface (via createAudioInput() in AudioBackendFactory)-// so the capture layer stays swappable, mirroring AudioBackend for output.+// (CoreAudioInput); Windows and Linux a miniaudio one, and Windows also AsioInput,+// which shares the running ASIO driver with AsioBackend instead of opening a device+// (specs/049). The engine talks only to this interface (via createAudioInput() in+// AudioBackendFactory) so the capture layer stays swappable, mirroring AudioBackend.#pragma oncediff --git a/src/native/nota.engine/src/audio_io/ConfigJson.cpp b/src/native/nota.engine/src/audio_io/ConfigJson.cppindex fe3627f7..2df51520 100644--- a/src/native/nota.engine/src/audio_io/ConfigJson.cpp+++ b/src/native/nota.engine/src/audio_io/ConfigJson.cpp@@ -60,6 +60,14 @@ AudioConfig loadAudioConfig() {cfg.sampleRate = getNumberTolerant(j, "sampleRate", 0.0);cfg.bufferFrames = static_cast<int32_t>(getNumberTolerant(j, "bufferFrames", 0.0));cfg.wasapiExclusive = getBoolTolerant(j, "wasapiExclusive", false);+ // ASIO (specs/049): missing keys keep today's behaviour (WASAPI); only Windows has ASIO.+#if defined(_WIN32)+ cfg.audioSystem = getStringTolerant(j, "audioSystem") == "asio" ? AudioSystem::Asio : AudioSystem::Wasapi;+#endif+ cfg.asioDriverClsid = getStringTolerant(j, "asioDriver");+ cfg.asioDriverName = getStringTolerant(j, "asioDriverName");+ cfg.asioOutputPair = std::max(0, static_cast<int32_t>(getNumberTolerant(j, "asioOutputPair", 0.0)));+ cfg.asioInputPair = std::max(0, static_cast<int32_t>(getNumberTolerant(j, "asioInputPair", 0.0)));} catch (...) {// Corrupt file -> defaults, like before.}@@ -75,6 +83,11 @@ void saveAudioConfig(const AudioConfig& cfg) {j["sampleRate"] = cfg.sampleRate;j["bufferFrames"] = cfg.bufferFrames;j["wasapiExclusive"] = cfg.wasapiExclusive;+ j["audioSystem"] = cfg.audioSystem == AudioSystem::Asio ? "asio" : "wasapi";+ j["asioDriver"] = cfg.asioDriverClsid;+ j["asioDriverName"] = cfg.asioDriverName;+ j["asioOutputPair"] = cfg.asioOutputPair;+ j["asioInputPair"] = cfg.asioInputPair;cfgfile::writeFileAtomic((std::filesystem::path(dir) / "audio.json").string(), j.dump(2) + "\n");}diff --git a/src/native/nota.engine/src/audio_io/asio/AsioDriverApi.h b/src/native/nota.engine/src/audio_io/asio/AsioDriverApi.hnew file mode 100644index 00000000..295b7618--- /dev/null+++ b/src/native/nota.engine/src/audio_io/asio/AsioDriverApi.h@@ -0,0 +1,84 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The subset of the ASIO driver interface (IASIO) that AsioSession uses (specs/049,+// research R3/R11), in our own types so the session builds on every platform. Windows+// adapts the real COM driver (windows/ComAsioDriver); the self-test uses FakeAsioDriver.+// Every call except outputReady() comes from the session's control side (never the audio+// thread); outputReady() is called from inside the buffer switch, as ASIO specifies.++#pragma once++#include "AsioSampleFormat.h"++#include <cstdint>+#include <string>++namespace nota::asio {++// asioMessage selectors (values from the SDK's asio.h).+enum MessageSelector : int32_t {+ kSelectorSupported = 1,+ kEngineVersion = 2,+ kResetRequest = 3,+ kBufferSizeChange = 4,+ kResyncRequest = 5,+ kLatenciesChanged = 6,+ kSupportsTimeInfo = 7,+ kSupportsTimeCode = 8,+ kOverload = 15,+};++struct ChannelInfo {+ int32_t index = 0;+ bool isInput = false;+ SampleType type = SampleType::Float32LSB;+ std::string name;+};++struct BufferInfo {+ bool isInput = false;+ int32_t channel = 0;+ void* buffers[2] = {nullptr, nullptr}; // filled by createBuffers+};++// Plain function pointers: ASIO callbacks carry no user data, so the session routes them+// through one static instance (one driver per process).+struct Callbacks {+ // `samplePosition` is the driver's running frame count, or -1 if it didn't report one.+ void (*bufferSwitch)(int32_t index, int64_t samplePosition) = nullptr;+ void (*sampleRateDidChange)(double rate) = nullptr;+ int32_t (*message)(int32_t selector, int32_t value) = nullptr;+};++class AsioDriverApi {+ public:+ virtual ~AsioDriverApi() = default;++ virtual bool init() = 0;+ virtual std::string driverName() = 0;+ virtual std::string errorMessage() = 0; // the driver's own text after a failure, may be ""+ virtual bool getChannels(int32_t& inputs, int32_t& outputs) = 0;+ virtual bool getBufferSize(int32_t& minSize, int32_t& maxSize, int32_t& preferred, int32_t& granularity) = 0;+ virtual bool canSampleRate(double rate) = 0;+ virtual bool getSampleRate(double& rate) = 0;+ virtual bool setSampleRate(double rate) = 0;+ virtual bool getChannelInfo(ChannelInfo& info) = 0; // index + isInput in, the rest out+ virtual bool createBuffers(BufferInfo* infos, int32_t count, int32_t bufferSize, const Callbacks& cb) = 0;+ virtual bool disposeBuffers() = 0;+ virtual bool start() = 0;+ virtual bool stop() = 0;+ virtual bool getLatencies(int32_t& input, int32_t& output) = 0;+ virtual bool controlPanel() = 0; // may return before the panel closes+ virtual bool outputReady() = 0; // false = not supported by this driver (buffer switch only)+ // The one-time "does it support outputReady" probe at open, from the control side: timed+ // like every other control call (outputReady() itself is direct, for the buffer switch).+ virtual bool probeOutputReady() { return outputReady(); }+ // True once a call timed out: the driver is abandoned and every later call fails fast.+ virtual bool timedOut() const { return false; }+ // True while the driver's own settings panel is open: it may hold the driver's thread+ // for as long as the user likes, so the session defers restarts until it closes.+ virtual bool panelOpen() const { return false; }+};++} // namespace nota::asiodiff --git a/src/native/nota.engine/src/audio_io/asio/AsioSampleFormat.cpp b/src/native/nota.engine/src/audio_io/asio/AsioSampleFormat.cppnew file mode 100644index 00000000..a76edae3--- /dev/null+++ b/src/native/nota.engine/src/audio_io/asio/AsioSampleFormat.cpp@@ -0,0 +1,202 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++#include "AsioSampleFormat.h"++#include <algorithm>+#include <cmath>+#include <cstring>++namespace nota::asio {+namespace {++// Significant bits of the 32-bit-container integer types.+int32_t int32Bits(SampleType t) {+ switch (t) {+ case SampleType::Int32LSB16: return 16;+ case SampleType::Int32LSB18: return 18;+ case SampleType::Int32LSB20: return 20;+ case SampleType::Int32LSB24: return 24;+ default: return 32;+ }+}++// Round a float to a signed integer of `bits` bits, clamped to [-2^(bits-1), 2^(bits-1) - 1].+inline int32_t quantize(float x, int32_t bits) {+ const double full = std::ldexp(1.0, bits - 1);+ double v = std::nearbyint(static_cast<double>(x) * full);+ v = std::clamp(v, -full, full - 1.0);+ return static_cast<int32_t>(v);+}++} // namespace++bool isSupported(SampleType t) {+ switch (t) {+ case SampleType::Int16LSB:+ case SampleType::Int24LSB:+ case SampleType::Int32LSB:+ case SampleType::Float32LSB:+ case SampleType::Float64LSB:+ case SampleType::Int32LSB16:+ case SampleType::Int32LSB18:+ case SampleType::Int32LSB20:+ case SampleType::Int32LSB24: return true;+ default: return false;+ }+}++int32_t bytesPerSample(SampleType t) {+ switch (t) {+ case SampleType::Int16LSB: return 2;+ case SampleType::Int24LSB: return 3;+ case SampleType::Float64LSB: return 8;+ case SampleType::Int32LSB:+ case SampleType::Float32LSB:+ case SampleType::Int32LSB16:+ case SampleType::Int32LSB18:+ case SampleType::Int32LSB20:+ case SampleType::Int32LSB24: return 4;+ default: return 0;+ }+}++const char* sampleTypeName(SampleType t) {+ switch (t) {+ case SampleType::Int16MSB: return "Int16MSB";+ case SampleType::Int24MSB: return "Int24MSB";+ case SampleType::Int32MSB: return "Int32MSB";+ case SampleType::Float32MSB: return "Float32MSB";+ case SampleType::Float64MSB: return "Float64MSB";+ case SampleType::Int32MSB16: return "Int32MSB16";+ case SampleType::Int32MSB18: return "Int32MSB18";+ case SampleType::Int32MSB20: return "Int32MSB20";+ case SampleType::Int32MSB24: return "Int32MSB24";+ case SampleType::Int16LSB: return "Int16LSB";+ case SampleType::Int24LSB: return "Int24LSB";+ case SampleType::Int32LSB: return "Int32LSB";+ case SampleType::Float32LSB: return "Float32LSB";+ case SampleType::Float64LSB: return "Float64LSB";+ case SampleType::Int32LSB16: return "Int32LSB16";+ case SampleType::Int32LSB18: return "Int32LSB18";+ case SampleType::Int32LSB20: return "Int32LSB20";+ case SampleType::Int32LSB24: return "Int32LSB24";+ case SampleType::DSDInt8LSB1: return "DSDInt8LSB1";+ case SampleType::DSDInt8MSB1: return "DSDInt8MSB1";+ case SampleType::DSDInt8NER8: return "DSDInt8NER8";+ }+ return "unknown";+}++// Byte-wise little-endian reads/writes: the buffers are the driver's, alignment unknown.+void toFloat(const void* src, SampleType t, float* dst, int32_t frames, int32_t stride) {+ const auto* b = static_cast<const uint8_t*>(src);+ switch (t) {+ case SampleType::Int16LSB:+ for (int32_t i = 0; i < frames; ++i) {+ const auto v = static_cast<int16_t>(static_cast<uint16_t>(b[i * 2] | (b[i * 2 + 1] << 8)));+ dst[i * stride] = static_cast<float>(v) * (1.0f / 32768.0f);+ }+ return;+ case SampleType::Int24LSB:+ for (int32_t i = 0; i < frames; ++i) {+ const uint8_t* p = b + i * 3;+ int32_t v = p[0] | (p[1] << 8) | (p[2] << 16);+ if (v & 0x800000) v -= 0x1000000; // sign-extend+ dst[i * stride] = static_cast<float>(v) * (1.0f / 8388608.0f);+ }+ return;+ case SampleType::Int32LSB:+ case SampleType::Int32LSB16:+ case SampleType::Int32LSB18:+ case SampleType::Int32LSB20:+ case SampleType::Int32LSB24: {+ const double scale = 1.0 / std::ldexp(1.0, int32Bits(t) - 1);+ for (int32_t i = 0; i < frames; ++i) {+ int32_t v;+ std::memcpy(&v, b + i * 4, 4);+ dst[i * stride] = static_cast<float>(v * scale);+ }+ return;+ }+ case SampleType::Float32LSB:+ for (int32_t i = 0; i < frames; ++i) std::memcpy(&dst[i * stride], b + i * 4, 4);+ return;+ case SampleType::Float64LSB:+ for (int32_t i = 0; i < frames; ++i) {+ double v;+ std::memcpy(&v, b + i * 8, 8);+ dst[i * stride] = static_cast<float>(v);+ }+ return;+ default:+ for (int32_t i = 0; i < frames; ++i) dst[i * stride] = 0.0f;+ return;+ }+}++void fromFloat(const float* src, int32_t stride, SampleType t, void* dst, int32_t frames) {+ auto* b = static_cast<uint8_t*>(dst);+ switch (t) {+ case SampleType::Int16LSB:+ for (int32_t i = 0; i < frames; ++i) {+ const auto v = static_cast<uint16_t>(quantize(src[i * stride], 16));+ b[i * 2] = static_cast<uint8_t>(v);+ b[i * 2 + 1] = static_cast<uint8_t>(v >> 8);+ }+ return;+ case SampleType::Int24LSB:+ for (int32_t i = 0; i < frames; ++i) {+ const auto v = static_cast<uint32_t>(quantize(src[i * stride], 24));+ b[i * 3] = static_cast<uint8_t>(v);+ b[i * 3 + 1] = static_cast<uint8_t>(v >> 8);+ b[i * 3 + 2] = static_cast<uint8_t>(v >> 16);+ }+ return;+ case SampleType::Int32LSB:+ case SampleType::Int32LSB16:+ case SampleType::Int32LSB18:+ case SampleType::Int32LSB20:+ case SampleType::Int32LSB24: {+ const int32_t bits = int32Bits(t);+ for (int32_t i = 0; i < frames; ++i) {+ const int32_t v = quantize(src[i * stride], bits);+ std::memcpy(b + i * 4, &v, 4);+ }+ return;+ }+ case SampleType::Float32LSB:+ for (int32_t i = 0; i < frames; ++i) std::memcpy(b + i * 4, &src[i * stride], 4);+ return;+ case SampleType::Float64LSB:+ for (int32_t i = 0; i < frames; ++i) {+ const double v = src[i * stride];+ std::memcpy(b + i * 8, &v, 8);+ }+ return;+ default: return;+ }+}++void clear(SampleType t, void* dst, int32_t frames) {+ // Zero is all-zero bytes in every PCM / float layout, so an unused channel of an MSB+ // type can be silenced too (DSD is not: it has no PCM zero, and is left alone).+ int32_t bytes = bytesPerSample(t);+ if (bytes == 0) {+ switch (t) {+ case SampleType::Int16MSB: bytes = 2; break;+ case SampleType::Int24MSB: bytes = 3; break;+ case SampleType::Float64MSB: bytes = 8; break;+ case SampleType::Int32MSB:+ case SampleType::Float32MSB:+ case SampleType::Int32MSB16:+ case SampleType::Int32MSB18:+ case SampleType::Int32MSB20:+ case SampleType::Int32MSB24: bytes = 4; break;+ default: break;+ }+ }+ if (bytes > 0 && dst) std::memset(dst, 0, static_cast<size_t>(bytes) * static_cast<size_t>(frames));+}++} // namespace nota::asiodiff --git a/src/native/nota.engine/src/audio_io/asio/AsioSampleFormat.h b/src/native/nota.engine/src/audio_io/asio/AsioSampleFormat.hnew file mode 100644index 00000000..2f4e27dc--- /dev/null+++ b/src/native/nota.engine/src/audio_io/asio/AsioSampleFormat.h@@ -0,0 +1,59 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// ASIO sample formats (specs/049, research R6). Our own mirror of the SDK's ASIOSampleType+// values, so the platform-independent ASIO core (and its self-test) builds without the SDK.+// The conversions are pure and real-time safe: no allocation, no locks.++#pragma once++#include <cstdint>++namespace nota::asio {++// Values match ASIOSampleType in the SDK's asio.h.+enum class SampleType : int32_t {+ Int16MSB = 0,+ Int24MSB = 1,+ Int32MSB = 2,+ Float32MSB = 3,+ Float64MSB = 4,+ Int32MSB16 = 8,+ Int32MSB18 = 9,+ Int32MSB20 = 10,+ Int32MSB24 = 11,+ Int16LSB = 16,+ Int24LSB = 17, // packed 3 bytes+ Int32LSB = 18,+ Float32LSB = 19,+ Float64LSB = 20,+ Int32LSB16 = 24, // 32-bit container, value in the low 16 bits+ Int32LSB18 = 25,+ Int32LSB20 = 26,+ Int32LSB24 = 27,+ DSDInt8LSB1 = 32,+ DSDInt8MSB1 = 33,+ DSDInt8NER8 = 40,+};++// True for the little-endian PCM / float types Nota converts; false for every MSB and DSD type.+bool isSupported(SampleType type);++// Bytes per sample in the driver buffer (0 for an unsupported type).+int32_t bytesPerSample(SampleType type);++// Short name for messages ("Int32LSB", "Float32MSB", …).+const char* sampleTypeName(SampleType type);++// One channel of driver samples -> float. `dst` is written every `dstStride` floats (2 for+// interleaved stereo). Integers scale by 1 / 2^(bits-1). Unsupported types write zeros.+void toFloat(const void* src, SampleType type, float* dst, int32_t frames, int32_t dstStride);++// Float, read every `srcStride` floats -> one channel of driver samples. Clamped to [-1, 1)+// and rounded for the integer types (no dither). Unsupported types write nothing.+void fromFloat(const float* src, int32_t srcStride, SampleType type, void* dst, int32_t frames);++// Silence in the driver's format: zero bytes for every PCM / float type, MSB included.+void clear(SampleType type, void* dst, int32_t frames);++} // namespace nota::asiodiff --git a/src/native/nota.engine/src/audio_io/asio/AsioSession.cpp b/src/native/nota.engine/src/audio_io/asio/AsioSession.cppnew file mode 100644index 00000000..b5b8266d--- /dev/null+++ b/src/native/nota.engine/src/audio_io/asio/AsioSession.cpp@@ -0,0 +1,384 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++#include "AsioSession.h"++#include <algorithm>+#include <thread>++namespace nota::asio {+namespace {++// ASIO callbacks carry no user data and a process opens one driver, so a single pointer+// routes them to the session that created the buffers.+std::atomic<AsioSession*> g_active{nullptr};++void onBufferSwitch(int32_t index, int64_t pos) {+ if (AsioSession* s = g_active.load(std::memory_order_acquire)) s->bufferSwitch(index, pos);+}+void onSampleRateDidChange(double rate) {+ if (AsioSession* s = g_active.load(std::memory_order_acquire)) s->sampleRateChanged(rate);+}+int32_t onMessage(int32_t selector, int32_t value) {+ AsioSession* s = g_active.load(std::memory_order_acquire);+ return s ? s->message(selector, value) : 0;+}++int64_t nowNs() {+ return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch())+ .count();+}++// A switch in flight finishes within one buffer; bound the wait in case it never does.+// False = it is still running: whatever it reads must not be freed.+bool waitOutSwitch(const std::atomic<bool>& inSwitch) {+ for (int i = 0; i < 500 && inSwitch.load(std::memory_order_seq_cst); ++i)+ std::this_thread::sleep_for(std::chrono::milliseconds(1));+ return !inSwitch.load(std::memory_order_seq_cst);+}++} // namespace++AsioSession::~AsioSession() {+ close();+}++void AsioSession::setRenderCallback(RenderCallback cb) {+ if (state_ != State::Running) render_ = std::move(cb);+}++void AsioSession::setXrunCallback(std::function<void()> cb) {+ if (state_ != State::Running) xrun_ = std::move(cb);+}++bool AsioSession::setInputCallback(const InputCallback* cb) {+ input_.store(cb, std::memory_order_seq_cst);+ return cb || waitOutSwitch(inSwitch_);+}++bool AsioSession::quiesce() {+ live_.store(nullptr, std::memory_order_seq_cst); // late switches are ignored from here on+ if (waitOutSwitch(inSwitch_)) return true;+ wedged_ = true;+ return false;+}++bool AsioSession::failOpen(Failure why, std::string detail) {+ if (driver_ && driver_->timedOut()) why = Failure::Timeout;+ fail(why, std::move(detail));+ return false;+}++void AsioSession::fail(Failure why, std::string detail) {+ releaseDriver();+ failure_ = why;+ failureDetail_ = std::move(detail);+ state_ = State::Failed;+}++bool AsioSession::open(std::unique_ptr<AsioDriverApi> driver, const Options& opt) {+ close();+ state_ = State::Closed;+ failure_ = Failure::None;+ failureDetail_.clear();+ driverName_.clear();+ rateRefused_ = false;+ driverRate_ = 0.0;+ if (wedged_) {+ // The callbacks can't tell an old driver from a new one: never open next to a switch+ // that is still stuck. The driver is released (its thread is the driver's problem).+ driver.reset();+ return failOpen(Failure::Timeout, "an earlier audio callback never returned — restart Nota to use ASIO again");+ }+ driver_ = std::move(driver);+ if (!driver_) return failOpen(Failure::LoadFailed, {});++ if (!driver_->init()) return failOpen(Failure::InitFailed, driver_->errorMessage());+ driverName_ = driver_->driverName();++ int32_t ins = 0, outs = 0;+ if (!driver_->getChannels(ins, outs)) return failOpen(Failure::InitFailed, driver_->errorMessage());+ if (outs <= 0) return failOpen(Failure::NoOutputs, {});++ // Sample rate: honour a request the driver supports; otherwise keep its rate (FR-007).+ double rate = 0.0;+ driver_->getSampleRate(rate);+ if (opt.sampleRate > 0.0 && opt.sampleRate != rate) {+ if (driver_->canSampleRate(opt.sampleRate) && driver_->setSampleRate(opt.sampleRate)) driver_->getSampleRate(rate);+ else rateRefused_ = true;+ }+ if (rate <= 0.0) return failOpen(Failure::InitFailed, "no sample clock");+ sampleRate_ = rate;++ // Buffer size: the driver's preferred one (FR-008: set in the driver's own panel).+ int32_t minSize = 0, maxSize = 0, preferred = 0, granularity = 0;+ if (!driver_->getBufferSize(minSize, maxSize, preferred, granularity))+ return failOpen(Failure::InitFailed, driver_->errorMessage());+ bufferFrames_ = preferred > 0 ? preferred : minSize;+ if (bufferFrames_ <= 0) return failOpen(Failure::InitFailed, "no buffer size");++ auto readChannels = [&](bool input, int32_t count, std::vector<ChannelInfo>& out) {+ out.clear();+ for (int32_t i = 0; i < count; ++i) {+ ChannelInfo ci;+ ci.index = i;+ ci.isInput = input;+ if (!driver_->getChannelInfo(ci)) return false;+ if (ci.name.empty()) ci.name = (input ? "In " : "Out ") + std::to_string(i + 1);+ out.push_back(std::move(ci));+ }+ return true;+ };+ if (!readChannels(false, outs, outChannels_) || !readChannels(true, ins, inChannels_))+ return failOpen(Failure::InitFailed, driver_->errorMessage());++ // Pairs: an out-of-range pair falls back to the first; a missing second channel = mono.+ outL_ = (opt.outputPair >= 0 && opt.outputPair < outs) ? opt.outputPair : 0;+ outR_ = outL_ + 1 < outs ? outL_ + 1 : -1;+ inL_ = ins > 0 ? ((opt.inputPair >= 0 && opt.inputPair < ins) ? opt.inputPair : 0) : -1;+ inR_ = (inL_ >= 0 && inL_ + 1 < ins) ? inL_ + 1 : -1;++ auto unsupported = [&](const ChannelInfo& c) { return !isSupported(c.type); };+ for (int32_t ch : {outL_, outR_})+ if (ch >= 0 && unsupported(outChannels_[ch]))+ return failOpen(Failure::UnsupportedFormat, sampleTypeName(outChannels_[ch].type));+ for (int32_t ch : {inL_, inR_})+ if (ch >= 0 && unsupported(inChannels_[ch]))+ return failOpen(Failure::UnsupportedFormat, sampleTypeName(inChannels_[ch].type));++ // Buffers for every output (so the unused ones can be held at zero, FR-006) and the+ // chosen input pair.+ io_ = std::make_unique<Io>();+ Io& io = *io_;+ io.driver = driver_.get();+ io.frames = bufferFrames_;+ for (int32_t i = 0; i < outs; ++i) {+ io.buffers.push_back(BufferInfo{false, i, {nullptr, nullptr}});+ io.outTypes.push_back(outChannels_[i].type);+ }+ io.outL = outL_;+ io.outR = outR_;+ if (inL_ >= 0) {+ io.inLBuf = static_cast<int32_t>(io.buffers.size());+ io.inLType = inChannels_[inL_].type;+ io.buffers.push_back(BufferInfo{true, inL_, {nullptr, nullptr}});+ }+ if (inR_ >= 0) {+ io.inRBuf = static_cast<int32_t>(io.buffers.size());+ io.inRType = inChannels_[inR_].type;+ io.buffers.push_back(BufferInfo{true, inR_, {nullptr, nullptr}});+ }+ io.interleaved.assign(static_cast<size_t>(bufferFrames_) * 2, 0.0f);++ g_active.store(this, std::memory_order_release); // the driver may message during createBuffers+ Callbacks cb;+ cb.bufferSwitch = &onBufferSwitch;+ cb.sampleRateDidChange = &onSampleRateDidChange;+ cb.message = &onMessage;+ if (!driver_->createBuffers(io.buffers.data(), static_cast<int32_t>(io.buffers.size()), bufferFrames_, cb))+ return failOpen(Failure::InitFailed, driver_->errorMessage());+ buffersCreated_ = true;+ for (const auto& b : io.buffers)+ if (!b.isInput)+ for (void* half : b.buffers) clear(io.outTypes[static_cast<size_t>(b.channel)], half, bufferFrames_);++ inputLatency_ = outputLatency_ = 0;+ driver_->getLatencies(inputLatency_, outputLatency_);+ io.outputReady = driver_->probeOutputReady(); // ASE_OK means supported+ resetRequested_.store(false, std::memory_order_relaxed);+ state_ = State::Prepared;+ return true;+}++bool AsioSession::start() {+ if (state_ == State::Running) return true;+ if (state_ != State::Prepared || !driver_ || !io_) return false;+ lastPosition_ = -1;+ lastTickNs_.store(nowNs(), std::memory_order_relaxed);+ io_->render = render_;+ live_.store(io_.get(), std::memory_order_seq_cst); // drivers may call back from inside start()+ if (!driver_->start()) {+ quiesce();+ return failOpen(Failure::InitFailed, driver_->errorMessage());+ }+ started_ = true;+ state_ = State::Running;+ return true;+}++void AsioSession::stop() {+ quiesce();+ if (started_ && driver_) driver_->stop();+ started_ = false;+ if (state_ == State::Running) state_ = State::Prepared;+}++void AsioSession::close() {+ stop();+ releaseDriver();+ if (state_ != State::Failed) state_ = State::Closed;+}++void AsioSession::releaseDriver() {+ if (quiesce()) {+ if (driver_) {+ if (started_) driver_->stop();+ if (buffersCreated_) driver_->disposeBuffers();+ }+ driver_.reset();+ io_.reset();+ } else {+ // A switch is still inside the render (a stalled plug-in) or the driver: freeing the+ // buffers, the driver or the scratch now would pull them out from under it. Leak them+ // on purpose; open() refuses from here on.+ (void)driver_.release();+ (void)io_.release();+ }+ started_ = false;+ buffersCreated_ = false;+ AsioSession* self = this;+ g_active.compare_exchange_strong(self, nullptr, std::memory_order_acq_rel);+ inChannels_.clear();+ outChannels_.clear();+ outL_ = outR_ = inL_ = inR_ = -1;+ sampleRate_ = 0.0;+ bufferFrames_ = 0;+ inputLatency_ = outputLatency_ = 0;+ if (state_ == State::Running || state_ == State::Prepared) state_ = State::Closed;+}++std::string AsioSession::failureText() const {+ std::string s;+ switch (failure_) {+ case Failure::None: return {};+ case Failure::NotInstalled: s = "the driver isn't installed"; break;+ case Failure::LoadFailed: s = "the driver couldn't be loaded"; break;+ case Failure::InitFailed: s = "the driver didn't start — another program may be using it"; break;+ case Failure::UnsupportedFormat: s = "the driver uses a sample format Nota can't read"; break;+ case Failure::NoOutputs: s = "the driver has no outputs"; break;+ case Failure::Timeout: s = "the driver stopped responding"; break;+ case Failure::Stopped: s = "the driver stopped sending audio"; break;+ }+ if (!failureDetail_.empty()) s += " (" + failureDetail_ + ")";+ return s;+}++bool AsioSession::openControlPanel() {+ return driver_ && (state_ == State::Prepared || state_ == State::Running) && driver_->controlPanel();+}++int32_t AsioSession::pollEvent() {+ // While the driver's own panel is open, events wait: restarting now would queue behind the+ // panel. The watchdog waits too — a driver may pause its buffers while its panel+ // reconfigures it, and that pause must not count as a failure once the panel closes.+ if (driver_ && driver_->panelOpen()) {+ lastTickNs_.store(nowNs(), std::memory_order_relaxed);+ return kEventNone;+ }+ // A pending reset comes first: it explains a silent spell (the driver stopped its buffers+ // to reconfigure) and reopening the driver is the right answer, not WASAPI.+ if (resetRequested_.exchange(false, std::memory_order_acq_rel)) {+ // Whatever the message was (many drivers send a plain reset request), a rate changed+ // in the driver's panel must survive the reopen — the engine stops asking for its own.+ double now = 0.0;+ if (driver_ && driver_->getSampleRate(now) && now > 0.0 && now != sampleRate_) driverRate_ = now;+ return kEventResetRequested;+ }+ if (state_ == State::Running) {+ const int64_t silentNs = nowNs() - lastTickNs_.load(std::memory_order_relaxed);+ if (silentNs > std::chrono::duration_cast<std::chrono::nanoseconds>(watchdog_).count()) {+ quiesce();+ failure_ = Failure::Stopped;+ failureDetail_.clear();+ state_ = State::Failed; // the driver is released by the next close() (the app re-applies)+ return kEventDriverFailed;+ }+ }+ return kEventNone;+}++// ---- audio thread ------------------------------------------------------------------------++void AsioSession::bufferSwitch(int32_t index, int64_t pos) {+ inSwitch_.store(true, std::memory_order_seq_cst);+ Io* const live = live_.load(std::memory_order_seq_cst); // pairs with quiesce()+ if (!live || index < 0 || index > 1) {+ inSwitch_.store(false, std::memory_order_release);+ return;+ }+ Io& s = *live; // everything below goes through this one object+ lastTickNs_.store(nowNs(), std::memory_order_relaxed);+ const int32_t n = s.frames;+ // A driver that changed its buffer size without a reset message shows up as a position+ // step that isn't a whole number of buffers: treat it as a reset request.+ if (pos >= 0) {+ if (lastPosition_ >= 0) {+ const int64_t step = pos - lastPosition_;+ if (step > 0 && step % n != 0) resetRequested_.store(true, std::memory_order_relaxed);+ }+ lastPosition_ = pos;+ }++ float* io = s.interleaved.data();+ // Input first, so the engine's input rings hold block n before block n renders (R2).+ if (const InputCallback* in = input_.load(std::memory_order_seq_cst); in && s.inLBuf >= 0) {+ toFloat(s.buffers[static_cast<size_t>(s.inLBuf)].buffers[index], s.inLType, io, n, 2);+ if (s.inRBuf >= 0) toFloat(s.buffers[static_cast<size_t>(s.inRBuf)].buffers[index], s.inRType, io + 1, n, 2);+ else+ for (int32_t i = 0; i < n; ++i) io[i * 2 + 1] = io[i * 2]; // mono input: both sides+ (*in)(io, n);+ }++ if (s.render) s.render(io, n);+ else std::fill(io, io + static_cast<size_t>(n) * 2, 0.0f);++ const auto outBuf = [&](int32_t ch) { return s.buffers[static_cast<size_t>(ch)].buffers[index]; };+ const auto outType = [&](int32_t ch) { return s.outTypes[static_cast<size_t>(ch)]; };+ if (s.outR >= 0) {+ fromFloat(io, 2, outType(s.outL), outBuf(s.outL), n);+ fromFloat(io + 1, 2, outType(s.outR), outBuf(s.outR), n);+ } else {+ for (int32_t i = 0; i < n; ++i) io[i * 2] = 0.5f * (io[i * 2] + io[i * 2 + 1]); // mono output: down-sum+ fromFloat(io, 2, outType(s.outL), outBuf(s.outL), n);+ }+ // Drivers may not keep buffer contents: hold every other output at zero each switch.+ const auto outs = static_cast<int32_t>(s.outTypes.size());+ for (int32_t ch = 0; ch < outs; ++ch)+ if (ch != s.outL && ch != s.outR) clear(outType(ch), outBuf(ch), n);++ if (s.outputReady) s.driver->outputReady();+ inSwitch_.store(false, std::memory_order_release);+}++// Driver threads (any): only flags and the lightweight xrun counter.+void AsioSession::sampleRateChanged(double) {+ resetRequested_.store(true, std::memory_order_relaxed);+}++int32_t AsioSession::message(int32_t selector, int32_t value) {+ switch (selector) {+ case kSelectorSupported:+ switch (value) {+ case kEngineVersion:+ case kResetRequest:+ case kBufferSizeChange:+ case kResyncRequest:+ case kLatenciesChanged:+ case kSupportsTimeInfo:+ case kOverload: return 1;+ default: return 0;+ }+ case kEngineVersion: return 2;+ case kResetRequest:+ case kBufferSizeChange:+ case kLatenciesChanged: resetRequested_.store(true, std::memory_order_relaxed); return 1;+ case kResyncRequest:+ case kOverload:+ if (xrun_) xrun_();+ return 1;+ case kSupportsTimeInfo: return 1;+ default: return 0;+ }+}++} // namespace nota::asiodiff --git a/src/native/nota.engine/src/audio_io/asio/AsioSession.h b/src/native/nota.engine/src/audio_io/asio/AsioSession.hnew file mode 100644index 00000000..f19a1738--- /dev/null+++ b/src/native/nota.engine/src/audio_io/asio/AsioSession.h@@ -0,0 +1,157 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// AsioSession — the one open ASIO driver (specs/049, research R2/R4). It backs both engine+// interfaces on Windows (AsioBackend for output, AsioInput for capture), so recording and+// playback share the driver's single duplex callback and clock. Platform-independent: it+// talks to the driver through AsioDriverApi, so FakeAsioDriver tests it on every platform.+//+// State machine (data-model.md): Closed -> (open) Prepared -> (start) Running; any failure+// -> Failed(reason) with the driver released. Control calls (open/start/stop/close/poll)+// come from one non-real-time thread. The buffer switch is the audio thread: it converts+// the chosen input pair, calls the input callback, renders, converts the result to the+// chosen output pair and zeroes every other output — no allocation, locks or I/O (AR-6).+// asioMessage only sets atomics; the app learns of resets / failures by polling.++#pragma once++#include "AsioDriverApi.h"+#include "audio_io/AudioBackend.h"+#include "audio_io/AudioInput.h"++#include <atomic>+#include <chrono>+#include <cstdint>+#include <functional>+#include <memory>+#include <string>+#include <vector>++namespace nota::asio {++class AsioSession {+ public:+ enum class State { Closed, Prepared, Running, Failed };+ enum class Failure { None, NotInstalled, LoadFailed, InitFailed, UnsupportedFormat, NoOutputs, Timeout, Stopped };+ // Values of NotaAudioDeviceEvent in the C ABI.+ enum DeviceEvent : int32_t { kEventNone = 0, kEventResetRequested = 1, kEventDriverFailed = 2 };++ struct Options {+ double sampleRate = 0.0; // 0 = keep the driver's rate+ int32_t outputPair = 0; // first channel of the output pair+ int32_t inputPair = 0; // first channel of the input pair+ };++ AsioSession() = default;+ ~AsioSession();+ AsioSession(const AsioSession&) = delete;+ AsioSession& operator=(const AsioSession&) = delete;++ // Take a created (loaded) driver and prepare it: init, sample rate, channels, buffers.+ // Prepared on success; Failed (driver released) otherwise.+ bool open(std::unique_ptr<AsioDriverApi> driver, const Options& opt);+ // Record a failure that happened before a driver existed (not installed / load / timeout).+ void fail(Failure why, std::string detail = {});++ // Set before start() (AR-6: never swapped while the driver calls back).+ void setRenderCallback(RenderCallback cb);+ void setXrunCallback(std::function<void()> cb);+ // Register (or, with nullptr, unregister) the capture callback; allowed while running.+ // The pointee must outlive the registration; unregistering waits out a switch in flight+ // and returns false if one never finished — then the pointee must be kept alive for good.+ bool setInputCallback(const InputCallback* cb);++ bool start();+ void stop();+ void close(); // stop, dispose the buffers and release the driver (FR-012)++ State state() const { return state_; }+ bool isRunning() const { return state_ == State::Running; }+ Failure failure() const { return failure_; }+ std::string failureText() const; // human reason, "" without a failure+ const std::string& driverName() const { return driverName_; }++ double sampleRate() const { return sampleRate_; }+ int32_t bufferFrames() const { return bufferFrames_; }+ int32_t inputLatency() const { return inputLatency_; }+ int32_t outputLatency() const { return outputLatency_; }+ bool sampleRateRefused() const { return rateRefused_; } // a requested rate the driver refused+ // The driver now runs at a different rate than the session opened with — set in the+ // driver's own panel. Read when a reset is reported; 0 if the rate didn't change.+ double driverChangedRate() const { return driverRate_; }+ bool hasInputs() const { return inL_ >= 0; }+ // A buffer switch never returned (a stalled plug-in or driver): its state is kept alive+ // and no driver opens again in this process.+ bool wedged() const { return wedged_; }+ const std::vector<ChannelInfo>& channels(bool input) const { return input ? inChannels_ : outChannels_; }+ int32_t outputPair() const { return outL_; }+ int32_t inputPair() const { return inL_; }++ bool openControlPanel();+ bool panelOpen() const { return driver_ && driver_->panelOpen(); }++ // Device event since the last call (cleared on read). Also runs the watchdog: a running+ // driver silent for longer than the timeout moves to Failed(Stopped).+ int32_t pollEvent();+ void setWatchdogTimeout(std::chrono::milliseconds t) { watchdog_ = t; }++ // Driver callbacks (routed here from the static trampolines).+ void bufferSwitch(int32_t index, int64_t samplePosition);+ void sampleRateChanged(double rate);+ int32_t message(int32_t selector, int32_t value);++ private:+ // Everything the buffer switch reads, built by open() and handed to the audio thread by+ // start(). Teardown takes it back only once no switch is running; a switch that never+ // returns keeps it (and the driver) alive for good rather than freeing memory under it.+ struct Io {+ AsioDriverApi* driver = nullptr;+ int32_t frames = 0;+ bool outputReady = false;+ std::vector<BufferInfo> buffers; // every output channel, then the chosen inputs+ std::vector<SampleType> outTypes;+ SampleType inLType = SampleType::Float32LSB, inRType = SampleType::Float32LSB;+ int32_t outL = -1, outR = -1; // output channels = their indices in buffers; R -1 = mono+ int32_t inLBuf = -1, inRBuf = -1; // indices into buffers (-1 = none / mono)+ std::vector<float> interleaved; // `frames` stereo frames+ RenderCallback render; // copied at start(): never swapped under the switch+ };++ void releaseDriver();+ bool failOpen(Failure why, std::string detail);+ bool quiesce(); // detach the audio thread from io_; false if a switch never finished++ std::unique_ptr<AsioDriverApi> driver_;+ std::unique_ptr<Io> io_;+ std::atomic<Io*> live_{nullptr}; // non-null while the buffer switch may run+ bool wedged_ = false;+ State state_ = State::Closed;+ Failure failure_ = Failure::None;+ std::string failureDetail_;+ std::string driverName_;+ bool buffersCreated_ = false;+ bool started_ = false; // driver_->start() succeeded and stop() is still owed++ double sampleRate_ = 0.0;+ int32_t bufferFrames_ = 0;+ int32_t inputLatency_ = 0;+ int32_t outputLatency_ = 0;+ bool rateRefused_ = false;+ double driverRate_ = 0.0; // see driverChangedRate()++ std::vector<ChannelInfo> inChannels_, outChannels_; // for the UI (control side only)+ int32_t outL_ = -1, outR_ = -1; // output channel indices (R -1 = mono)+ int32_t inL_ = -1, inR_ = -1; // input channel indices (-1 = none / mono)++ RenderCallback render_;+ std::function<void()> xrun_;+ std::atomic<const InputCallback*> input_{nullptr};++ std::atomic<bool> inSwitch_{false};+ std::atomic<bool> resetRequested_{false};+ std::atomic<int64_t> lastTickNs_{0};+ int64_t lastPosition_ = -1; // audio thread only+ std::chrono::milliseconds watchdog_{2000};+};++} // namespace nota::asiodiff --git a/src/native/nota.engine/src/audio_io/asio/FakeAsioDriver.cpp b/src/native/nota.engine/src/audio_io/asio/FakeAsioDriver.cppnew file mode 100644index 00000000..8c97a0c3--- /dev/null+++ b/src/native/nota.engine/src/audio_io/asio/FakeAsioDriver.cpp@@ -0,0 +1,156 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++#include "FakeAsioDriver.h"++#include <algorithm>++namespace nota::asio {++FakeAsioDriver::FakeAsioDriver(Config cfg) : cfg_(std::move(cfg)) {+ outTypes_.assign(static_cast<size_t>(std::max(0, cfg_.outputs)), cfg_.outputType);+ written_.resize(outTypes_.size());+ nonZero_.assign(outTypes_.size(), false);+}++bool FakeAsioDriver::init() {+ if (cfg_.initFails) {+ error_ = "device busy";+ return false;+ }+ initialized_ = true;+ return true;+}++bool FakeAsioDriver::getChannels(int32_t& inputs, int32_t& outputs) {+ if (!initialized_) return false;+ inputs = cfg_.inputs;+ outputs = cfg_.outputs;+ return true;+}++bool FakeAsioDriver::getBufferSize(int32_t& minSize, int32_t& maxSize, int32_t& preferred, int32_t& granularity) {+ minSize = maxSize = preferred = cfg_.bufferFrames;+ granularity = 0;+ return initialized_;+}++bool FakeAsioDriver::canSampleRate(double rate) {+ return std::find(cfg_.sampleRates.begin(), cfg_.sampleRates.end(), rate) != cfg_.sampleRates.end();+}++bool FakeAsioDriver::getSampleRate(double& rate) {+ rate = cfg_.sampleRate;+ return true;+}++bool FakeAsioDriver::setSampleRate(double rate) {+ if (!canSampleRate(rate)) return false;+ cfg_.sampleRate = rate;+ return true;+}++bool FakeAsioDriver::getChannelInfo(ChannelInfo& info) {+ const int32_t count = info.isInput ? cfg_.inputs : cfg_.outputs;+ if (info.index < 0 || info.index >= count) return false;+ info.type = info.isInput ? cfg_.inputType : outTypes_[static_cast<size_t>(info.index)];+ info.name = std::string(info.isInput ? "Fake In " : "Fake Out ") + std::to_string(info.index + 1);+ return true;+}++void FakeAsioDriver::setOutputType(int32_t channel, SampleType type) {+ if (channel >= 0 && channel < static_cast<int32_t>(outTypes_.size())) outTypes_[static_cast<size_t>(channel)] = type;+}++bool FakeAsioDriver::createBuffers(BufferInfo* infos, int32_t count, int32_t bufferSize, const Callbacks& cb) {+ if (!initialized_ || !infos || count <= 0 || bufferSize <= 0) return false;+ cb_ = cb;+ bufferFrames_ = bufferSize;+ infos_.assign(infos, infos + count);+ storage_.assign(static_cast<size_t>(count) * 2, {});+ for (int32_t i = 0; i < count; ++i) {+ auto& bi = infos[i];+ // 8 bytes per sample covers every type; fill with a pattern the host must overwrite.+ for (int half = 0; half < 2; ++half) {+ auto& mem = storage_[static_cast<size_t>(i) * 2 + half];+ mem.assign(static_cast<size_t>(bufferSize) * 8, 0x55);+ bi.buffers[half] = mem.data();+ }+ infos_[static_cast<size_t>(i)] = bi;+ }+ return true;+}++bool FakeAsioDriver::disposeBuffers() {+ infos_.clear();+ storage_.clear();+ return true;+}++bool FakeAsioDriver::start() {+ if (infos_.empty()) return false;+ running_ = true;+ return true;+}++bool FakeAsioDriver::stop() {+ running_ = false;+ return true;+}++bool FakeAsioDriver::getLatencies(int32_t& input, int32_t& output) {+ input = cfg_.inputLatency;+ output = cfg_.outputLatency;+ return true;+}++bool FakeAsioDriver::outputReady() {+ if (!cfg_.supportsOutputReady) return false;+ if (running_) ++outputReadyCalls_;+ return true;+}++void FakeAsioDriver::pump(int32_t count, bool evenIfStopped) {+ if (!cb_.bufferSwitch || silent_ || (!running_ && !evenIfStopped)) return;+ const size_t n = static_cast<size_t>(bufferFrames_);+ for (int32_t s = 0; s < count; ++s) {+ const int32_t half = switches_ & 1;+ std::vector<float> tmp(n);+ for (size_t i = 0; i < infos_.size(); ++i) {+ const BufferInfo& bi = infos_[i];+ void* buf = bi.buffers[half];+ if (bi.isInput) {+ for (size_t f = 0; f < n; ++f)+ tmp[f] = cfg_.inputSignal ? cfg_.inputSignal(bi.channel, position_ + static_cast<int64_t>(f)) : 0.0f;+ fromFloat(tmp.data(), 1, cfg_.inputType, buf, bufferFrames_);+ } else {+ std::fill_n(static_cast<uint8_t*>(buf), n * 8, uint8_t{0x55}); // stale garbage+ }+ }+ cb_.bufferSwitch(half, position_);+ for (const BufferInfo& bi : infos_) {+ if (bi.isInput) continue;+ const auto ch = static_cast<size_t>(bi.channel);+ const SampleType t = outTypes_[ch];+ const auto* bytes = static_cast<const uint8_t*>(bi.buffers[half]);+ const size_t width = static_cast<size_t>(std::max(1, bytesPerSample(t)));+ for (size_t b = 0; b < n * width; ++b)+ if (bytes[b] != 0) nonZero_[ch] = true;+ toFloat(bi.buffers[half], t, tmp.data(), bufferFrames_, 1);+ written_[ch].insert(written_[ch].end(), tmp.begin(), tmp.end());+ }+ position_ += positionStep_ > 0 ? positionStep_ : bufferFrames_;+ ++switches_;+ }+}++int32_t FakeAsioDriver::sendMessage(int32_t selector, int32_t value) {+ return cb_.message ? cb_.message(selector, value) : 0;+}++void FakeAsioDriver::changeSampleRate(double rate) {+ cfg_.sampleRate = rate;+ if (cb_.sampleRateDidChange) cb_.sampleRateDidChange(rate);+}++} // namespace nota::asiodiff --git a/src/native/nota.engine/src/audio_io/asio/FakeAsioDriver.h b/src/native/nota.engine/src/audio_io/asio/FakeAsioDriver.hnew file mode 100644index 00000000..488edfb7--- /dev/null+++ b/src/native/nota.engine/src/audio_io/asio/FakeAsioDriver.h@@ -0,0 +1,102 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// FakeAsioDriver — a scripted AsioDriverApi for nota_asio_selftest (specs/049, research+// R11). Configurable channels, sample types, buffer size, rates and latencies; a scripted+// input signal; switches for "init fails" and "stops calling back". pump(n) drives n buffer+// switches synchronously on the caller's thread and records what the host wrote to every+// output channel, so tests are deterministic on every platform.++#pragma once++#include "AsioDriverApi.h"++#include <cstdint>+#include <functional>+#include <string>+#include <vector>++namespace nota::asio {++class FakeAsioDriver final : public AsioDriverApi {+ public:+ struct Config {+ int32_t inputs = 2;+ int32_t outputs = 2;+ SampleType inputType = SampleType::Float32LSB;+ SampleType outputType = SampleType::Float32LSB;+ int32_t bufferFrames = 64;+ double sampleRate = 48000.0;+ std::vector<double> sampleRates{44100.0, 48000.0};+ int32_t inputLatency = 0;+ int32_t outputLatency = 0;+ bool initFails = false;+ bool supportsOutputReady = true;+ // Input channel `ch` at absolute frame `frame` (nullptr = silence).+ std::function<float(int32_t ch, int64_t frame)> inputSignal;+ };++ explicit FakeAsioDriver(Config cfg);++ // ---- AsioDriverApi ----+ bool init() override;+ std::string driverName() override { return "Fake ASIO"; }+ std::string errorMessage() override { return error_; }+ bool getChannels(int32_t& inputs, int32_t& outputs) override;+ bool getBufferSize(int32_t& minSize, int32_t& maxSize, int32_t& preferred, int32_t& granularity) override;+ bool canSampleRate(double rate) override;+ bool getSampleRate(double& rate) override;+ bool setSampleRate(double rate) override;+ bool getChannelInfo(ChannelInfo& info) override;+ bool createBuffers(BufferInfo* infos, int32_t count, int32_t bufferSize, const Callbacks& cb) override;+ bool disposeBuffers() override;+ bool start() override;+ bool stop() override;+ bool getLatencies(int32_t& input, int32_t& output) override;+ bool controlPanel() override { return true; }+ bool outputReady() override;+ bool panelOpen() const override { return panelOpen_; }++ // ---- test controls ----+ // Run `switches` buffer switches (alternating halves). Does nothing while stopped unless+ // `evenIfStopped` (a late callback after stop()), or while "stops calling back" is set.+ void pump(int32_t switches, bool evenIfStopped = false);+ void setStopsCallingBack(bool on) { silent_ = on; }+ void setPanelOpen(bool on) { panelOpen_ = on; } // the user has the driver's panel open+ // Advance the reported sample position by this many frames per switch (0 = the buffer+ // size); a different value imitates a buffer-size change with no reset message.+ void setPositionStep(int32_t frames) { positionStep_ = frames; }+ int32_t sendMessage(int32_t selector, int32_t value = 0);+ void changeSampleRate(double rate); // the driver's clock moved: sampleRateDidChange+ // Change one output channel's type (before the host opens the driver).+ void setOutputType(int32_t channel, SampleType type);++ // What the host wrote to output `ch`, per switch, as float (in the channel's format).+ const std::vector<float>& written(int32_t ch) const { return written_[static_cast<size_t>(ch)]; }+ // True if any byte the host left in output `ch` after a switch was non-zero.+ bool nonZeroBytes(int32_t ch) const { return nonZero_[static_cast<size_t>(ch)]; }+ int32_t switches() const { return switches_; }+ int32_t outputReadyCalls() const { return outputReadyCalls_; }+ bool running() const { return running_; }++ private:+ Config cfg_;+ std::vector<SampleType> outTypes_;+ std::string error_;+ bool initialized_ = false;+ bool running_ = false;+ bool silent_ = false;+ bool panelOpen_ = false;+ Callbacks cb_;+ int32_t bufferFrames_ = 0;+ std::vector<BufferInfo> infos_;+ std::vector<std::vector<uint8_t>> storage_; // two halves per BufferInfo+ std::vector<std::vector<float>> written_;+ std::vector<bool> nonZero_;+ int32_t switches_ = 0;+ int32_t outputReadyCalls_ = 0;+ int32_t positionStep_ = 0;+ int64_t position_ = 0;+};++} // namespace nota::asiodiff --git a/src/native/nota.engine/src/audio_io/windows/AsioBackend.cpp b/src/native/nota.engine/src/audio_io/windows/AsioBackend.cppnew file mode 100644index 00000000..3c5abac7--- /dev/null+++ b/src/native/nota.engine/src/audio_io/windows/AsioBackend.cpp@@ -0,0 +1,111 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++#include "AsioBackend.h"++#if defined(_WIN32)++#include "AsioDriverList.h"+#include "ComAsioDriver.h"++namespace nota::asio {++AsioSession& sharedAsioSession() {+ // Never destroyed: releasing a driver joins its COM thread, which must not happen during+ // DLL unload. The engine closes the session when it stops the backend.+ static AsioSession* session = new AsioSession();+ return *session;+}++} // namespace nota::asio++namespace nota {++using asio::AsioSession;+using asio::sharedAsioSession;++AsioBackend::~AsioBackend() {+ stop();+}++bool AsioBackend::start(RenderCallback render, const BackendConfig& cfg) {+ AsioSession& s = sharedAsioSession();+ s.close();+ reason_.clear();++ const auto drivers = asio::enumerateAsioDrivers();+ const asio::AsioDriverInfo* d = asio::findAsioDriver(drivers, cfg.asioDriverClsid, cfg.asioDriverName);+ if (!d && cfg.asioDriverClsid.empty() && cfg.asioDriverName.empty() && !drivers.empty())+ d = &drivers.front(); // ASIO chosen but no driver yet: the first installed one+ if (!d) {+ s.fail(AsioSession::Failure::NotInstalled);+ reason_ = s.failureText();+ return false;+ }++ bool timedOut = false;+ std::string error;+ auto driver = asio::ComAsioDriver::create(d->clsid, timedOut, error);+ if (!driver) {+ s.fail(timedOut ? AsioSession::Failure::Timeout : AsioSession::Failure::LoadFailed, error);+ reason_ = s.failureText();+ return false;+ }++ s.setRenderCallback(std::move(render));+ s.setXrunCallback(xrun_);+ AsioSession::Options opt;+ opt.sampleRate = cfg.sampleRate;+ opt.outputPair = cfg.asioOutputPair;+ opt.inputPair = cfg.asioInputPair;+ if (!s.open(std::move(driver), opt) || !s.start()) {+ reason_ = s.failureText();+ s.close();+ return false;+ }+ return true;+}++void AsioBackend::stop() {+ AsioSession& s = sharedAsioSession();+ if (s.state() != AsioSession::State::Closed) s.close();+}++double AsioBackend::sampleRate() const {+ return sharedAsioSession().sampleRate();+}++int32_t AsioBackend::bufferFrames() const {+ return sharedAsioSession().bufferFrames();+}++bool AsioBackend::isRunning() const {+ return sharedAsioSession().isRunning();+}++int32_t AsioBackend::inputLatencyFrames() const {+ return sharedAsioSession().inputLatency();+}++int32_t AsioBackend::outputLatencyFrames() const {+ return sharedAsioSession().outputLatency();+}++int32_t AsioBackend::pollDeviceEvent() {+ AsioSession& s = sharedAsioSession();+ const int32_t ev = s.pollEvent();+ if (ev == AsioSession::kEventDriverFailed) reason_ = s.failureText(); // for the engine's fallback+ return ev;+}++double AsioBackend::deviceChangedRate() const {+ return sharedAsioSession().driverChangedRate();+}++bool AsioBackend::sampleRateRefused() const {+ return sharedAsioSession().sampleRateRefused();+}++} // namespace nota++#endif // defined(_WIN32)diff --git a/src/native/nota.engine/src/audio_io/windows/AsioBackend.h b/src/native/nota.engine/src/audio_io/windows/AsioBackend.hnew file mode 100644index 00000000..b67964c7--- /dev/null+++ b/src/native/nota.engine/src/audio_io/windows/AsioBackend.h@@ -0,0 +1,52 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// AsioBackend — AudioBackend over the process-wide AsioSession (specs/049, research R2).+// start() finds the configured driver (CLSID, then name), loads it through ComAsioDriver,+// applies the requested sample rate if the driver supports it, opens the chosen output+// pair and starts. The driver decides the buffer size (FR-008). stop() releases the driver+// so other programs can use it (FR-012). A failed start() leaves a reason for the engine's+// WASAPI fallback (FR-011).++#pragma once++#include "audio_io/AudioBackend.h"+#include "audio_io/asio/AsioSession.h"++#include <functional>+#include <string>++namespace nota::asio {++// The one ASIO session of the process, shared by AsioBackend and AsioInput.+AsioSession& sharedAsioSession();++} // namespace nota::asio++namespace nota {++class AsioBackend final : public AudioBackend {+ public:+ ~AsioBackend() override;++ bool start(RenderCallback render, const BackendConfig& cfg) override;+ void stop() override;+ double sampleRate() const override;+ int32_t bufferFrames() const override;+ bool isRunning() const override;+ void setXrunCallback(std::function<void()> cb) override { xrun_ = std::move(cb); }++ int32_t inputLatencyFrames() const override;+ int32_t outputLatencyFrames() const override;+ bool sharesInputClock() const override { return true; }+ int32_t pollDeviceEvent() override;+ const char* fallbackReason() const override { return reason_.c_str(); }+ bool sampleRateRefused() const override;+ double deviceChangedRate() const override;++ private:+ std::function<void()> xrun_;+ std::string reason_;+};++} // namespace notadiff --git a/src/native/nota.engine/src/audio_io/windows/AsioDriverList.cpp b/src/native/nota.engine/src/audio_io/windows/AsioDriverList.cppnew file mode 100644index 00000000..bd62f73f--- /dev/null+++ b/src/native/nota.engine/src/audio_io/windows/AsioDriverList.cpp@@ -0,0 +1,90 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++#include "AsioDriverList.h"++#if defined(_WIN32)++#include <windows.h>++#include <algorithm>+#include <cwctype>++namespace nota::asio {+namespace {++std::string toUtf8(const std::wstring& w) {+ if (w.empty()) return {};+ const int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), static_cast<int>(w.size()), nullptr, 0, nullptr, nullptr);+ std::string s(static_cast<size_t>(n), '\0');+ WideCharToMultiByte(CP_UTF8, 0, w.data(), static_cast<int>(w.size()), s.data(), n, nullptr, nullptr);+ return s;+}++std::wstring readString(HKEY key, const wchar_t* value) {+ DWORD type = 0, bytes = 0;+ if (RegQueryValueExW(key, value, nullptr, &type, nullptr, &bytes) != ERROR_SUCCESS || type != REG_SZ || bytes == 0)+ return {};+ std::wstring s(bytes / sizeof(wchar_t), L'\0');+ if (RegQueryValueExW(key, value, nullptr, nullptr, reinterpret_cast<LPBYTE>(s.data()), &bytes) != ERROR_SUCCESS)+ return {};+ while (!s.empty() && s.back() == L'\0') s.pop_back();+ return s;+}++bool sameClsid(const std::string& a, const std::string& b) {+ return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin(), [](char x, char y) {+ return std::towlower(static_cast<unsigned char>(x)) == std::towlower(static_cast<unsigned char>(y));+ });+}++} // namespace++std::vector<AsioDriverInfo> enumerateAsioDrivers() {+ std::vector<AsioDriverInfo> list;+ HKEY root = nullptr;+ if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\ASIO", 0, KEY_READ, &root) != ERROR_SUCCESS) return list;+ for (DWORD i = 0;; ++i) {+ wchar_t keyName[256];+ DWORD len = 256;+ const LONG r = RegEnumKeyExW(root, i, keyName, &len, nullptr, nullptr, nullptr, nullptr);+ if (r == ERROR_NO_MORE_ITEMS) break;+ if (r != ERROR_SUCCESS) continue;+ HKEY sub = nullptr;+ if (RegOpenKeyExW(root, keyName, 0, KEY_READ, &sub) != ERROR_SUCCESS) continue;+ const std::wstring clsid = readString(sub, L"CLSID");+ const std::wstring description = readString(sub, L"Description");+ RegCloseKey(sub);+ if (clsid.empty()) continue;+ AsioDriverInfo d;+ d.clsid = toUtf8(clsid);+ d.name = toUtf8(std::wstring(keyName, len));+ d.displayName = description.empty() ? d.name : toUtf8(description);+ list.push_back(std::move(d));+ }+ RegCloseKey(root);++ // Two drivers may share a display name (two interfaces of one maker): number the rest.+ std::vector<std::string> base;+ for (const auto& d : list) base.push_back(d.displayName);+ for (size_t i = 0; i < list.size(); ++i) {+ const auto same = 1 + std::count(base.begin(), base.begin() + static_cast<std::ptrdiff_t>(i), base[i]);+ if (same > 1) list[i].displayName += " (" + std::to_string(same) + ")";+ }+ return list;+}++const AsioDriverInfo* findAsioDriver(const std::vector<AsioDriverInfo>& drivers, const std::string& clsid,+ const std::string& name) {+ if (!clsid.empty())+ for (const auto& d : drivers)+ if (sameClsid(d.clsid, clsid)) return &d;+ if (!name.empty())+ for (const auto& d : drivers)+ if (d.name == name) return &d;+ return nullptr;+}++} // namespace nota::asio++#endif // defined(_WIN32)diff --git a/src/native/nota.engine/src/audio_io/windows/AsioDriverList.h b/src/native/nota.engine/src/audio_io/windows/AsioDriverList.hnew file mode 100644index 00000000..2fbe3335--- /dev/null+++ b/src/native/nota.engine/src/audio_io/windows/AsioDriverList.h@@ -0,0 +1,28 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Installed ASIO drivers (specs/049, research R3/R10), read from+// HKEY_LOCAL_MACHINE\SOFTWARE\ASIO in the process's native registry view — a 64-bit build+// never sees the 32-bit drivers under WOW6432Node, and an ARM64 build sees ARM64 ones.++#pragma once++#include <string>+#include <vector>++namespace nota::asio {++struct AsioDriverInfo {+ std::string clsid; // "{xxxxxxxx-…}" as stored in the registry+ std::string name; // the registry key name+ std::string displayName; // name, with " (2)", " (3)" added to duplicates+};++std::vector<AsioDriverInfo> enumerateAsioDrivers();++// The driver matching `clsid`, else one whose name matches `name` (a reinstalled driver+// may come back with a new CLSID). nullptr if neither matches.+const AsioDriverInfo* findAsioDriver(const std::vector<AsioDriverInfo>& drivers, const std::string& clsid,+ const std::string& name);++} // namespace nota::asiodiff --git a/src/native/nota.engine/src/audio_io/windows/AsioInput.cpp b/src/native/nota.engine/src/audio_io/windows/AsioInput.cppnew file mode 100644index 00000000..0894db23--- /dev/null+++ b/src/native/nota.engine/src/audio_io/windows/AsioInput.cpp@@ -0,0 +1,43 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++#include "AsioInput.h"++#if defined(_WIN32)++#include "AsioBackend.h"++namespace nota {++AsioInput::~AsioInput() {+ stop();+}++bool AsioInput::start(InputCallback cb, uint32_t) {+ if (registered_) return isRunning();+ auto& s = asio::sharedAsioSession();+ if (!s.isRunning() || !s.hasInputs()) return false; // no driver, or one without inputs+ cb_ = new InputCallback(std::move(cb));+ s.setInputCallback(cb_);+ registered_ = true;+ return true;+}++void AsioInput::stop() {+ if (!registered_) return;+ if (asio::sharedAsioSession().setInputCallback(nullptr)) delete cb_; // else a switch may still call it+ registered_ = false;+ cb_ = nullptr;+}++bool AsioInput::isRunning() const {+ return registered_ && asio::sharedAsioSession().isRunning();+}++double AsioInput::sampleRate() const {+ return asio::sharedAsioSession().sampleRate();+}++} // namespace nota++#endif // defined(_WIN32)diff --git a/src/native/nota.engine/src/audio_io/windows/AsioInput.h b/src/native/nota.engine/src/audio_io/windows/AsioInput.hnew file mode 100644index 00000000..131bc84a--- /dev/null+++ b/src/native/nota.engine/src/audio_io/windows/AsioInput.h@@ -0,0 +1,31 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// AsioInput — AudioInput over the shared AsioSession (specs/049, research R2). It never+// opens a second driver: start() registers the capture callback with the session the+// AsioBackend already runs, so input and output share one callback and clock. The device+// argument is ignored — the input pair is part of the session's configuration.++#pragma once++#include "audio_io/AudioInput.h"++namespace nota {++class AsioInput final : public AudioInput {+ public:+ ~AsioInput() override;++ bool start(InputCallback cb, uint32_t device = 0) override;+ void stop() override;+ bool isRunning() const override;+ double sampleRate() const override;++ private:+ // Registered by address while running. Heap-held: if unregistering finds a buffer switch+ // that never returned, the callback is leaked rather than freed under it.+ InputCallback* cb_ = nullptr;+ bool registered_ = false;+};++} // namespace notadiff --git a/src/native/nota.engine/src/audio_io/windows/ComAsioDriver.cpp b/src/native/nota.engine/src/audio_io/windows/ComAsioDriver.cppnew file mode 100644index 00000000..723a4903--- /dev/null+++ b/src/native/nota.engine/src/audio_io/windows/ComAsioDriver.cpp@@ -0,0 +1,419 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.++#include "ComAsioDriver.h"++#if defined(_WIN32)++#include <windows.h>+#include <objbase.h>+#include <avrt.h>++// Steinberg ASIO SDK headers (GPLv3 option; LICENSES/third-party.md note 8).+#include "asiosys.h"+#include "asio.h"+#include "iasiodrv.h"++#include <atomic>+#include <cstdio>+#include <cstring>+#include <deque>+#include <functional>+#include <future>+#include <mutex>+#include <vector>++namespace nota::asio {++struct ComAsioDriver::Shared {+ std::mutex m;+ std::deque<std::function<void()>> queue;+ HANDLE wake = CreateEventW(nullptr, FALSE, FALSE, nullptr);+ bool quit = false; // control thread only+ IASIO* drv = nullptr; // created, used and released on the control thread+ HWND window = nullptr; // the driver's sysHandle (parent of its panel)+ std::atomic<bool> abandoned{false};+ std::atomic<bool> panelOpen{false}; // inside drv->controlPanel()+ std::promise<void> exited; // set by the thread after Release() + CoUninitialize()++ ~Shared() {+ if (wake) CloseHandle(wake);+ }+ void post(std::function<void()> fn) {+ {+ std::lock_guard<std::mutex> lock(m);+ queue.push_back(std::move(fn));+ }+ SetEvent(wake);+ }+};++namespace {++constexpr unsigned kLoadTimeoutMs = 5000;+constexpr unsigned kCallTimeoutMs = 2000;++// The SDK's ASIOCallbacks hold plain function pointers and must stay valid while buffers+// exist; one driver per process, so one static set forwards to the session's callbacks.+Callbacks g_cb;+// Open only between createBuffers and disposeBuffers of a live driver. An abandoned driver+// (a call timed out) is cut off here, and no other driver opens until Nota restarts: its+// thread may still be inside the driver and call back later, and ASIO callbacks carry+// nothing that tells two drivers apart.+std::atomic<bool> g_routeOpen{false};+std::atomic<bool> g_driverAbandoned{false};++void abandon(ComAsioDriver::Shared& sh) {+ sh.abandoned.store(true);+ g_routeOpen.store(false, std::memory_order_release);+ g_driverAbandoned.store(true);+}++void ensureProAudioThread() {+ // The buffer thread is the engine's audio thread: make sure it runs under MMCSS+ // "Pro Audio" if the driver didn't already raise it (ASIO SDK 2.3 § MMCSS). Once per thread.+ thread_local bool done = false;+ if (done) return;+ done = true;+ if (GetThreadPriority(GetCurrentThread()) >= THREAD_PRIORITY_TIME_CRITICAL) return;+ DWORD task = 0;+ AvSetMmThreadCharacteristicsW(L"Pro Audio", &task);+}++void sdkBufferSwitch(long index, ASIOBool) {+ if (!g_routeOpen.load(std::memory_order_acquire)) return;+ ensureProAudioThread();+ if (g_cb.bufferSwitch) g_cb.bufferSwitch(static_cast<int32_t>(index), -1);+}++ASIOTime* sdkBufferSwitchTimeInfo(ASIOTime* t, long index, ASIOBool) {+ if (!g_routeOpen.load(std::memory_order_acquire)) return t;+ ensureProAudioThread();+ int64_t pos = -1;+ if (t && (t->timeInfo.flags & kSamplePositionValid))+ pos = static_cast<int64_t>((static_cast<uint64_t>(t->timeInfo.samplePosition.hi) << 32) |+ static_cast<uint64_t>(t->timeInfo.samplePosition.lo));+ if (g_cb.bufferSwitch) g_cb.bufferSwitch(static_cast<int32_t>(index), pos);+ return t;+}++void sdkSampleRateDidChange(ASIOSampleRate rate) {+ if (g_routeOpen.load(std::memory_order_acquire) && g_cb.sampleRateDidChange) g_cb.sampleRateDidChange(rate);+}++long sdkAsioMessage(long selector, long value, void*, double*) {+ // Messages also arrive inside createBuffers (time-info queries), before the route opens.+ return g_cb.message && !g_driverAbandoned.load() ? g_cb.message(static_cast<int32_t>(selector), static_cast<int32_t>(value)) : 0;+}++ASIOCallbacks g_sdkCallbacks = {&sdkBufferSwitch, &sdkSampleRateDidChange, &sdkAsioMessage,+ &sdkBufferSwitchTimeInfo};++std::string ansiToUtf8(const char* s) {+ if (!s || !*s) return {};+ const int wn = MultiByteToWideChar(CP_ACP, 0, s, -1, nullptr, 0);+ std::wstring w(static_cast<size_t>(wn), L'\0');+ MultiByteToWideChar(CP_ACP, 0, s, -1, w.data(), wn);+ const int n = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, nullptr, 0, nullptr, nullptr);+ std::string out(static_cast<size_t>(n), '\0');+ WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, out.data(), n, nullptr, nullptr);+ while (!out.empty() && out.back() == '\0') out.pop_back();+ return out;+}++void controlThread(std::shared_ptr<ComAsioDriver::Shared> sh) {+ CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);+ sh->window = CreateWindowExW(0, L"STATIC", L"Nota ASIO", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr,+ GetModuleHandleW(nullptr), nullptr);+ while (!sh->quit) {+ MsgWaitForMultipleObjects(1, &sh->wake, FALSE, INFINITE, QS_ALLINPUT);+ for (;;) {+ std::function<void()> fn;+ {+ std::lock_guard<std::mutex> lock(sh->m);+ if (sh->queue.empty()) break;+ fn = std::move(sh->queue.front());+ sh->queue.pop_front();+ }+ fn();+ }+ MSG msg;+ while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {+ TranslateMessage(&msg);+ DispatchMessageW(&msg);+ }+ }+ if (sh->drv) sh->drv->Release();+ sh->drv = nullptr;+ if (sh->window) DestroyWindow(sh->window);+ CoUninitialize();+ sh->exited.set_value();+}++} // namespace++ComAsioDriver::ComAsioDriver()+ : sh_(std::make_shared<Shared>()), exited_(sh_->exited.get_future()), thread_(controlThread, sh_) {}++ComAsioDriver::~ComAsioDriver() {+ if (!sh_->abandoned.load()) {+ // The thread releases the driver on its way out; wait for that, not just for the+ // quit task, so a Release() that hangs can't hang the caller in join().+ sh_->post([sh = sh_] { sh->quit = true; });+ if (exited_.wait_for(std::chrono::milliseconds(kCallTimeoutMs)) == std::future_status::ready) {+ thread_.join();+ return;+ }+ abandon(*sh_);+ }+ thread_.detach(); // stuck inside the driver: leave it (and the driver object) behind+}++// Run `fn` on the control thread and wait. Everything `fn` touches must be captured by+// value or shared_ptr: after a timeout the caller is gone but the task may still run.+template <class F> bool ComAsioDriver::call(F fn, unsigned timeoutMs) {+ if (sh_->abandoned.load()) return false;+ auto done = std::make_shared<std::promise<void>>();+ auto fut = done->get_future();+ sh_->post([fn = std::move(fn), done]() mutable {+ fn();+ done->set_value();+ });+ // Never wait open-ended here: the caller is the UI thread. While the driver's panel is open+ // the app holds restarts back (nota_audio_asio_panel_open), so a call stuck behind the+ // panel only happens on the way out of Nota — where giving up on the driver is fine.+ if (fut.wait_for(std::chrono::milliseconds(timeoutMs)) == std::future_status::ready) return true;+ abandon(*sh_);+ return false;+}++std::unique_ptr<ComAsioDriver> ComAsioDriver::create(const std::string& clsid, bool& timedOut, std::string& error) {+ timedOut = false;+ if (g_driverAbandoned.load()) {+ error = "an earlier ASIO driver stopped responding — restart Nota to use ASIO again";+ return nullptr;+ }+ const int wn = MultiByteToWideChar(CP_UTF8, 0, clsid.c_str(), -1, nullptr, 0);+ std::wstring w(static_cast<size_t>(wn > 0 ? wn : 1), L'\0');+ MultiByteToWideChar(CP_UTF8, 0, clsid.c_str(), -1, w.data(), wn);+ CLSID id{};+ if (CLSIDFromString(w.c_str(), &id) != NOERROR) {+ error = "bad CLSID";+ return nullptr;+ }+ std::unique_ptr<ComAsioDriver> d(new ComAsioDriver());+ auto hr = std::make_shared<HRESULT>(E_FAIL);+ // ASIO drivers register their CLSID as the interface id too.+ if (!d->call(+ [sh = d->sh_, id, hr] {+ IASIO* p = nullptr;+ *hr = CoCreateInstance(id, nullptr, CLSCTX_INPROC_SERVER, id, reinterpret_cast<void**>(&p));+ if (SUCCEEDED(*hr)) sh->drv = p;+ },+ kLoadTimeoutMs)) {+ timedOut = true;+ error = "timed out";+ return nullptr;+ }+ if (FAILED(*hr)) {+ char buf[32];+ snprintf(buf, sizeof buf, "0x%08lX", static_cast<unsigned long>(*hr));+ error = buf;+ return nullptr;+ }+ return d;+}++bool ComAsioDriver::timedOut() const {+ return sh_->abandoned.load();+}++bool ComAsioDriver::panelOpen() const {+ return sh_->panelOpen.load();+}++bool ComAsioDriver::init() {+ auto ok = std::make_shared<bool>(false);+ return call([sh = sh_, ok] { *ok = sh->drv && sh->drv->init(sh->window) == ASIOTrue; }, kLoadTimeoutMs) && *ok;+}++std::string ComAsioDriver::driverName() {+ auto s = std::make_shared<std::string>();+ // After a timeout the abandoned task may still write *s: never read it then.+ if (!call(+ [sh = sh_, s] {+ char name[128] = {};+ if (sh->drv) sh->drv->getDriverName(name);+ *s = ansiToUtf8(name);+ },+ kCallTimeoutMs))+ return {};+ return *s;+}++std::string ComAsioDriver::errorMessage() {+ auto s = std::make_shared<std::string>();+ if (!call(+ [sh = sh_, s] {+ char text[256] = {};+ if (sh->drv) sh->drv->getErrorMessage(text);+ *s = ansiToUtf8(text);+ },+ kCallTimeoutMs))+ return {};+ return *s;+}++bool ComAsioDriver::getChannels(int32_t& inputs, int32_t& outputs) {+ struct R {+ long in = 0, out = 0;+ ASIOError e = ASE_NotPresent;+ };+ auto r = std::make_shared<R>();+ if (!call([sh = sh_, r] { if (sh->drv) r->e = sh->drv->getChannels(&r->in, &r->out); }, kCallTimeoutMs) ||+ r->e != ASE_OK)+ return false;+ inputs = static_cast<int32_t>(r->in);+ outputs = static_cast<int32_t>(r->out);+ return true;+}++bool ComAsioDriver::getBufferSize(int32_t& minSize, int32_t& maxSize, int32_t& preferred, int32_t& granularity) {+ struct R {+ long mn = 0, mx = 0, pref = 0, gran = 0;+ ASIOError e = ASE_NotPresent;+ };+ auto r = std::make_shared<R>();+ if (!call([sh = sh_, r] { if (sh->drv) r->e = sh->drv->getBufferSize(&r->mn, &r->mx, &r->pref, &r->gran); },+ kCallTimeoutMs) ||+ r->e != ASE_OK)+ return false;+ minSize = static_cast<int32_t>(r->mn);+ maxSize = static_cast<int32_t>(r->mx);+ preferred = static_cast<int32_t>(r->pref);+ granularity = static_cast<int32_t>(r->gran);+ return true;+}++bool ComAsioDriver::canSampleRate(double rate) {+ auto e = std::make_shared<ASIOError>(ASE_NotPresent);+ return call([sh = sh_, e, rate] { if (sh->drv) *e = sh->drv->canSampleRate(rate); }, kCallTimeoutMs) &&+ *e == ASE_OK;+}++bool ComAsioDriver::getSampleRate(double& rate) {+ struct R {+ ASIOSampleRate rate = 0.0;+ ASIOError e = ASE_NotPresent;+ };+ auto r = std::make_shared<R>();+ if (!call([sh = sh_, r] { if (sh->drv) r->e = sh->drv->getSampleRate(&r->rate); }, kCallTimeoutMs) ||+ r->e != ASE_OK)+ return false;+ rate = r->rate;+ return true;+}++bool ComAsioDriver::setSampleRate(double rate) {+ auto e = std::make_shared<ASIOError>(ASE_NotPresent);+ return call([sh = sh_, e, rate] { if (sh->drv) *e = sh->drv->setSampleRate(rate); }, kLoadTimeoutMs) &&+ *e == ASE_OK;+}++bool ComAsioDriver::getChannelInfo(ChannelInfo& info) {+ auto ci = std::make_shared<ASIOChannelInfo>();+ ci->channel = info.index;+ ci->isInput = info.isInput ? ASIOTrue : ASIOFalse;+ auto e = std::make_shared<ASIOError>(ASE_NotPresent);+ if (!call([sh = sh_, ci, e] { if (sh->drv) *e = sh->drv->getChannelInfo(ci.get()); }, kCallTimeoutMs) ||+ *e != ASE_OK)+ return false;+ info.type = static_cast<SampleType>(ci->type);+ char name[33] = {};+ memcpy(name, ci->name, 32);+ info.name = ansiToUtf8(name);+ return true;+}++bool ComAsioDriver::createBuffers(BufferInfo* infos, int32_t count, int32_t bufferSize, const Callbacks& cb) {+ if (!infos || count <= 0) return false;+ g_cb = cb;+ auto sdk = std::make_shared<std::vector<ASIOBufferInfo>>(static_cast<size_t>(count));+ for (int32_t i = 0; i < count; ++i) {+ (*sdk)[i].isInput = infos[i].isInput ? ASIOTrue : ASIOFalse;+ (*sdk)[i].channelNum = infos[i].channel;+ (*sdk)[i].buffers[0] = (*sdk)[i].buffers[1] = nullptr;+ }+ auto e = std::make_shared<ASIOError>(ASE_NotPresent);+ if (!call(+ [sh = sh_, sdk, e, bufferSize] {+ if (sh->drv)+ *e = sh->drv->createBuffers(sdk->data(), static_cast<long>(sdk->size()), bufferSize,+ &g_sdkCallbacks);+ },+ kLoadTimeoutMs) ||+ *e != ASE_OK)+ return false;+ for (int32_t i = 0; i < count; ++i) {+ infos[i].buffers[0] = (*sdk)[i].buffers[0];+ infos[i].buffers[1] = (*sdk)[i].buffers[1];+ }+ g_routeOpen.store(true, std::memory_order_release);+ return true;+}++bool ComAsioDriver::disposeBuffers() {+ g_routeOpen.store(false, std::memory_order_release); // the session has already stopped the driver+ auto e = std::make_shared<ASIOError>(ASE_NotPresent);+ return call([sh = sh_, e] { if (sh->drv) *e = sh->drv->disposeBuffers(); }, kCallTimeoutMs) && *e == ASE_OK;+}++bool ComAsioDriver::start() {+ auto e = std::make_shared<ASIOError>(ASE_NotPresent);+ return call([sh = sh_, e] { if (sh->drv) *e = sh->drv->start(); }, kLoadTimeoutMs) && *e == ASE_OK;+}++bool ComAsioDriver::stop() {+ auto e = std::make_shared<ASIOError>(ASE_NotPresent);+ return call([sh = sh_, e] { if (sh->drv) *e = sh->drv->stop(); }, kCallTimeoutMs) && *e == ASE_OK;+}++bool ComAsioDriver::getLatencies(int32_t& input, int32_t& output) {+ struct R {+ long in = 0, out = 0;+ ASIOError e = ASE_NotPresent;+ };+ auto r = std::make_shared<R>();+ if (!call([sh = sh_, r] { if (sh->drv) r->e = sh->drv->getLatencies(&r->in, &r->out); }, kCallTimeoutMs) ||+ r->e != ASE_OK)+ return false;+ input = static_cast<int32_t>(r->in);+ output = static_cast<int32_t>(r->out);+ return true;+}++bool ComAsioDriver::controlPanel() {+ // Posted, not waited on: the panel may be modal and stay open for as long as the user likes.+ if (sh_->abandoned.load()) return false;+ sh_->panelOpen.store(true); // before posting: a reset sent at once must already wait+ sh_->post([sh = sh_] {+ if (sh->drv) sh->drv->controlPanel();+ sh->panelOpen.store(false);+ });+ return true;+}++bool ComAsioDriver::probeOutputReady() {+ auto e = std::make_shared<ASIOError>(ASE_NotPresent);+ return call([sh = sh_, e] { if (sh->drv) *e = sh->drv->outputReady(); }, kCallTimeoutMs) && *e == ASE_OK;+}++bool ComAsioDriver::outputReady() {+ // From the buffer switch (and once from the session to probe support): a direct call.+ IASIO* d = sh_->drv;+ return d && !sh_->abandoned.load(std::memory_order_relaxed) && d->outputReady() == ASE_OK;+}++} // namespace nota::asio++#endif // defined(_WIN32)diff --git a/src/native/nota.engine/src/audio_io/windows/ComAsioDriver.h b/src/native/nota.engine/src/audio_io/windows/ComAsioDriver.hnew file mode 100644index 00000000..2656f38a--- /dev/null+++ b/src/native/nota.engine/src/audio_io/windows/ComAsioDriver.h@@ -0,0 +1,61 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// ComAsioDriver — AsioDriverApi over a real ASIO driver's COM interface (IASIO, from the+// SDK's iasiodrv.h; specs/049, research R3/R4). The driver object lives on a dedicated+// control thread (COINIT_APARTMENTTHREADED, pumping messages for the driver's own windows):+// every call is posted there and waited on with a timeout — 5 s to create / init, 2 s+// otherwise — so a hung driver can't hang Nota (SC-005). After a timeout the driver is+// abandoned: every later call fails fast and the thread is left to the driver.+// outputReady() is the exception: ASIO calls it from inside the buffer switch.++#pragma once++#include "audio_io/asio/AsioDriverApi.h"++#include <future>+#include <memory>+#include <string>+#include <thread>++namespace nota::asio {++class ComAsioDriver final : public AsioDriverApi {+ public:+ // Create the driver registered under `clsid`. nullptr on failure; `timedOut` tells a+ // hung driver from one that refused to load, `error` says why.+ static std::unique_ptr<ComAsioDriver> create(const std::string& clsid, bool& timedOut, std::string& error);+ ~ComAsioDriver() override;++ bool init() override;+ std::string driverName() override;+ std::string errorMessage() override;+ bool getChannels(int32_t& inputs, int32_t& outputs) override;+ bool getBufferSize(int32_t& minSize, int32_t& maxSize, int32_t& preferred, int32_t& granularity) override;+ bool canSampleRate(double rate) override;+ bool getSampleRate(double& rate) override;+ bool setSampleRate(double rate) override;+ bool getChannelInfo(ChannelInfo& info) override;+ bool createBuffers(BufferInfo* infos, int32_t count, int32_t bufferSize, const Callbacks& cb) override;+ bool disposeBuffers() override;+ bool start() override;+ bool stop() override;+ bool getLatencies(int32_t& input, int32_t& output) override;+ bool controlPanel() override;+ bool outputReady() override;+ bool probeOutputReady() override;+ bool timedOut() const override;+ bool panelOpen() const override;++ struct Shared; // the control thread's state; outlives this object if the thread is abandoned++ private:+ ComAsioDriver();+ template <class F> bool call(F fn, unsigned timeoutMs);++ std::shared_ptr<Shared> sh_;+ std::future<void> exited_; // ready once the control thread has released the driver+ std::thread thread_;+};++} // namespace nota::asiodiff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cppindex 07a3794c..6832eb6a 100644--- a/src/native/nota.engine/src/engine/Engine.cpp+++ b/src/native/nota.engine/src/engine/Engine.cpp@@ -12,7 +12,9 @@#include "media/WarpStream.h" // complete ClipWarpStream for wb_.stream (unique_ptr) destruction#include <algorithm>+#include <chrono>#include <cmath>+#include <utility>namespace nota {@@ -47,18 +49,62 @@ Engine::~Engine() {bool Engine::start() {if (backend_->isRunning()) return true;+ // The audio system the config asks for (specs/049): ASIO only where the build has it.+ const AudioSystem wanted = asioSupported() ? config_.audioSystem : AudioSystem::Wasapi;+ // A driver that went silent while running isn't retried by the restart its failure+ // triggers — it could start, stay silent and fail again forever. That restart runs+ // WASAPI; the next apply (the user's) tries ASIO again.+ const std::string skipAsio = std::exchange(asioSkipOnce_, std::string{});+ const bool skipping = wanted == AudioSystem::Asio && !skipAsio.empty();+ const AudioSystem first = skipping ? AudioSystem::Wasapi : wanted;+ if (first != activeSystem_) {+ backend_ = createAudioBackend(first);+ activeSystem_ = first;+ }+ audioFallbackReason_ = skipping ? skipAsio : std::string{};transport_.setSampleRate(backend_->sampleRate() > 0 ? backend_->sampleRate() : 44100.0);BackendConfig bc;bc.device = resolveAudioDeviceId(config_.outputDeviceUid, /*inputScope=*/false);bc.sampleRate = config_.sampleRate;bc.bufferFrames = config_.bufferFrames;bc.wasapiExclusive = config_.wasapiExclusive;+ bc.asioDriverClsid = config_.asioDriverClsid;+ bc.asioDriverName = config_.asioDriverName;+ bc.asioOutputPair = config_.asioOutputPair;+ bc.asioInputPair = config_.asioInputPair;+ if (skipping) { // the fallback runs on the system default device+ bc = BackendConfig{};+ bc.device = resolveAudioDeviceId(std::string{}, /*inputScope=*/false);+ }backend_->setXrunCallback([this] { notifyXrun(); }); // device dropouts (M7-8)// The device rate is only known once the backend is open, so the nodes are re-prepared// after it starts. Until then the callback must stay out of the graph: prepare()// reallocates buffers (and hosted plugins run prepareToPlay) the audio thread would read.- renderSuspended_.store(true, std::memory_order_release);- const bool ok = backend_->start([this](float* out, int32_t n) { render(out, n); }, bc);+ renderSuspended_.store(true, std::memory_order_seq_cst);+ // A previous device's callback may still be inside render() — an ASIO driver given up on+ // while a plug-in stalled. Re-preparing the nodes under it would corrupt them: wait for it+ // to leave, and if it never does, stay off rather than run two renders over one graph.+ for (int i = 0; i < 2000 && rendersInFlight_.load(std::memory_order_seq_cst) > 0; ++i)+ std::this_thread::sleep_for(std::chrono::milliseconds(1));+ if (rendersInFlight_.load(std::memory_order_seq_cst) > 0) {+ audioFallbackReason_ = "a plug-in stopped responding inside the audio callback — restart Nota";+ return false;+ }+ bool ok = backend_->start([this](float* out, int32_t n) { render(out, n); }, bc);+ if (!ok && activeSystem_ == AudioSystem::Asio) {+ // FR-011: a missing, busy or broken ASIO driver never leaves Nota silent — run WASAPI+ // on the system default device and say why. The saved choice stays ASIO, so the next+ // apply (or launch) tries the driver again.+ const char* why = backend_->fallbackReason();+ audioFallbackReason_ = why && *why ? why : "the driver didn't start";+ backend_ = createAudioBackend(AudioSystem::Wasapi);+ activeSystem_ = AudioSystem::Wasapi;+ BackendConfig fallback;+ fallback.device = resolveAudioDeviceId(std::string{}, /*inputScope=*/false);+ backend_->setXrunCallback([this] { notifyXrun(); });+ ok = backend_->start([this](float* out, int32_t n) { render(out, n); }, fallback);+ }+ monitorSharedClock_.store(ok && backend_->sharesInputClock(), std::memory_order_relaxed);if (ok) {transport_.setSampleRate(backend_->sampleRate());propagateSampleRate(backend_->sampleRate()); // re-prepare every node (incl. master + racks) at the new rate@@ -167,6 +213,33 @@ void Engine::setAudioBufferFrames(int32_t f) {void Engine::setAudioWasapiExclusive(bool on) {config_.wasapiExclusive = on;}+int32_t Engine::pollAudioDeviceEvent() {+ const int32_t ev = backend_ ? backend_->pollDeviceEvent() : 0;+ if (ev == 1 && config_.sampleRate > 0.0 && backend_->deviceChangedRate() > 0.0) {+ // The user changed the rate in the driver's panel: follow the driver from now on+ // ("device default") instead of putting the old saved rate back on reopen.+ config_.sampleRate = 0.0;+ saveAudioConfig(config_);+ }+ if (ev == 2 && activeSystem_ == AudioSystem::Asio) {+ const char* why = backend_->fallbackReason();+ asioSkipOnce_ = why && *why ? why : "the driver stopped sending audio";+ }+ return ev;+}++void Engine::setAudioSystem(AudioSystem system) {+ if (asioSupported()) config_.audioSystem = system;+}+void Engine::setAsioDriver(const std::string& clsid, const std::string& name) {+ if (!asioSupported()) return;+ config_.asioDriverClsid = clsid;+ config_.asioDriverName = name;+}+void Engine::setAsioPair(bool input, int32_t firstChannel) {+ if (!asioSupported()) return;+ (input ? config_.asioInputPair : config_.asioOutputPair) = std::max(0, firstChannel);+}bool Engine::applyAudioConfig() {saveAudioConfig(config_);@@ -174,6 +247,12 @@ bool Engine::applyAudioConfig() {// Drop the cached input unit so the next capture re-opens the chosen device.if (input_) input_.reset();const bool ok = start();+ // A rate the ASIO driver refused isn't kept: the driver's own rate runs, and the saved+ // config says "device default" so the next launch doesn't ask again (FR-007).+ if (activeSystem_ == AudioSystem::Asio && backend_->sampleRateRefused() && config_.sampleRate > 0.0) {+ config_.sampleRate = 0.0;+ saveAudioConfig(config_);+ }// Live monitoring held the old capture device open: reopen on the chosen one.hwRecordTap_.store(false, std::memory_order_relaxed);hwMonitorTap_.store(false, std::memory_order_relaxed);diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex 8c25766e..101fefa2 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -76,6 +76,28 @@ class Engine {bool audioSilentFallback() const { return backend_ ? backend_->silentFallback() : false; }int32_t bufferFrames() const { return backend_ ? backend_->bufferFrames() : 0; }+ // --- ASIO (Windows; specs/049) ---+ // Staged like the rest of the config; applyAudioConfig() persists and restarts. Off+ // Windows the setters change nothing (the native backend is the only system).+ void setAudioSystem(AudioSystem system);+ void setAsioDriver(const std::string& clsid, const std::string& name);+ void setAsioPair(bool input, int32_t firstChannel);+ // What actually runs: Wasapi after a failed ASIO start fell back (FR-011).+ AudioSystem activeAudioSystem() const { return activeSystem_; }+ // Why the last ASIO start failed ("" if it didn't, or ASIO wasn't asked for).+ const std::string& audioFallbackReason() const { return audioFallbackReason_; }+ // Device event since the last call (0 none, 1 reset requested, 2 driver failed).+ // A driver that stopped calling back makes the next start skip ASIO once (FR-011).+ int32_t pollAudioDeviceEvent();+ int32_t audioInputLatencyFrames() const { return backend_ ? backend_->inputLatencyFrames() : 0; }+ int32_t audioOutputLatencyFrames() const { return backend_ ? backend_->outputLatencyFrames() : 0; }++ // Where a hardware take really starts once the device's round-trip latency is taken+ // out (research R7): `latencyFrames` earlier, in device frames. A take that would+ // start before beat 0 stays at 0 and drops its first frames instead (`trimFrames`).+ static double latencyCompensatedStart(double startBeat, int32_t latencyFrames, double samplesPerBeat,+ double* trimFrames);+// --- MIDI device settings (M7-2) ---// Which inputs the engine listens to; persisted as a blocklist of disabled// uids in midi.json (empty = all on). Setters stage midiConfig_; apply@@ -1203,6 +1225,9 @@ class Engine {void setTrackMonitor(int32_t trackId, bool on);bool trackMonitor(int32_t trackId) const;void pushMonitorFramesForTest(const float* interleavedStereo, int32_t frames); // feed the hw monitor ring+ // Device-free: under a shared input clock (ASIO) one driver block rendered in two segments+ // (a loop boundary) reaches monitoring whole — the rest of the block isn't trimmed as stale.+ bool monitorSharedClockSelfTest();// MIDI routing: forward an instrument track's MIDI to another instrument track (-1 = off).void setTrackMidiSource(int32_t trackId, int32_t sourceTrackId);int32_t trackMidiSource(int32_t trackId) const;@@ -1465,6 +1490,9 @@ class Engine {std::unique_ptr<AudioBackend> backend_;AudioConfig config_; // chosen device/rate/buffer (M7-1)+ AudioSystem activeSystem_ = AudioSystem::Wasapi; // what backend_ is (after any fallback)+ std::string audioFallbackReason_; // why ASIO didn't start (specs/049)+ std::string asioSkipOnce_; // set when the running driver went silent: the next start runs WASAPIMidiConfig midiConfig_; // enabled MIDI inputs (M7-2)std::unique_ptr<MidiInput> midiInput_;std::unique_ptr<GamepadInput> gamepadInput_; // game controller note input@@ -1670,6 +1698,9 @@ class Engine {// Set by start() before the device opens, cleared (release) once every node is re-prepared// at the negotiated rate: while set, render() outputs silence and never touches the graph.std::atomic<bool> renderSuspended_{false};+ // Device callbacks inside render() right now. start() waits for 0 before re-preparing+ // nodes: a render stuck in a plug-in (an ASIO driver given up on) must not overlap it.+ std::atomic<int32_t> rendersInFlight_{0};std::atomic<double> launchQuant_{4.0}; // Session launch quantize, beats (M5-2)// Arrangement playback active (M5): true after main Play / arrangement record; false in a// session-only jam. Read on the audio thread to gate arrangement clip content per track.@@ -1945,6 +1976,7 @@ class Engine {std::vector<float> monitorHwBuf_; // audio thread, this segment's hw inputbool monitorPrimed_ = false; // audio thread: cushion reachedstd::atomic<int32_t> inputBlockFrames_{0}; // largest capture callback seen (cushion size)+ std::atomic<bool> monitorSharedClock_{false}; // capture shares the output callback (ASIO): no cushionstd::atomic<bool> hwMonitorTap_{false}; // input thread -> monitorQueue_std::atomic<bool> hwRecordTap_{false}; // input thread -> inputQueue_ (hw take rolling)bool hwMonitorWanted_ = false; // message thread: some track monitors hw input@@ -1976,6 +2008,7 @@ class Engine {int32_t audioRecordTrackId_ = 0;double audioRecordStartBeat_ = 0.0;double audioRecordSampleRate_ = 0.0;+ int32_t audioRecordLatencyFrames_ = 0; // device round trip to take out of a hardware take// Internal-resampling source for the active take (0 = hardware/off, -1 = master,// >0 = source track id). Read on the audio thread in mixGraph to tap the ring.std::atomic<int32_t> internalRecordSource_{0};diff --git a/src/native/nota.engine/src/engine/Engine_Recording.cpp b/src/native/nota.engine/src/engine/Engine_Recording.cppindex 930e6a7a..ad4d07be 100644--- a/src/native/nota.engine/src/engine/Engine_Recording.cpp+++ b/src/native/nota.engine/src/engine/Engine_Recording.cpp@@ -76,8 +76,11 @@ bool Engine::trackMonitor(int32_t trackId) const {bool Engine::ensureAudioInput() {if (inputTestMode_) return true;if (input_ && input_->isRunning()) return true;- if (!input_) input_ = createAudioInput();- const uint32_t inputDev = resolveAudioDeviceId(config_.inputDeviceUid, /*inputScope=*/true);+ if (!input_) input_ = createAudioInput(activeSystem_); // ASIO: the running driver's inputs+ // In the ASIO → WASAPI fallback the output runs on the system default; so does capture.+ // The saved WASAPI input stays as it is for when WASAPI is chosen.+ const bool asioFallback = asioSupported() && config_.audioSystem == AudioSystem::Asio && activeSystem_ != AudioSystem::Asio;+ const uint32_t inputDev = resolveAudioDeviceId(asioFallback ? std::string{} : config_.inputDeviceUid, /*inputScope=*/true);// The input thread only touches the lock-free rings (RT-safe).return input_->start([this](const float* s, int32_t n) {@@ -132,13 +135,19 @@ void Engine::pullMonitorInput(int32_t frames) {monitorPrimed_ = false;return;}- const size_t cushion = static_cast<size_t>(std::clamp(inputBlockFrames_.load(std::memory_order_relaxed), 64, 4096));- size_t avail = monitorQueue_.size();+ const size_t block = static_cast<size_t>(std::clamp(inputBlockFrames_.load(std::memory_order_relaxed), 64, 4096));const size_t n = static_cast<size_t>(frames);+ // ASIO duplex pushes a whole driver block before rendering it (one clock), so nothing has+ // to be primed (R8). But render may split that block into segments (a loop boundary): the+ // rest of the current block is not a backlog — only input older than one block is.+ const bool sharedClock = monitorSharedClock_.load(std::memory_order_relaxed);+ const size_t cushion = sharedClock ? 0 : block;+ const size_t keep = sharedClock ? std::max(block, n) : n + cushion;+ size_t avail = monitorQueue_.size();InputFrame f;- if (avail > n + cushion * 2 + 256) { // drifted / stalled: drop the stale backlog- for (size_t k = avail - (n + cushion); k > 0 && monitorQueue_.pop(f); --k) {}- avail = n + cushion;+ if (avail > keep + cushion + 256) { // drifted / stalled: drop the stale backlog+ for (size_t k = avail - keep; k > 0 && monitorQueue_.pop(f); --k) {}+ avail = keep;}if (!monitorPrimed_) {if (avail < n + cushion) return; // still filling the cushion: silence@@ -158,6 +167,32 @@ void Engine::pushMonitorFramesForTest(const float* interleavedStereo, int32_t frfor (int32_t i = 0; i < frames; ++i)monitorQueue_.push(InputFrame{interleavedStereo[i * 2], interleavedStereo[i * 2 + 1]});}+bool Engine::monitorSharedClockSelfTest() {+ constexpr int32_t kBlock = 512, kFirst = 10;+ const bool sharedWas = monitorSharedClock_.load();+ const int32_t blockWas = inputBlockFrames_.load();+ const bool tapWas = hwMonitorTap_.load();+ InputFrame f;+ while (monitorQueue_.pop(f)) {}+ monitorSharedClock_.store(true);+ inputBlockFrames_.store(kBlock);+ hwMonitorTap_.store(true);+ monitorPrimed_ = false;+ for (int32_t i = 0; i < kBlock; ++i) monitorQueue_.push(InputFrame{static_cast<float>(i), -static_cast<float>(i)});+ bool ok = true;+ pullMonitorInput(kFirst);+ for (int32_t i = 0; i < kFirst; ++i) ok = ok && monitorHwBuf_[i * 2] == static_cast<float>(i);+ pullMonitorInput(kBlock - kFirst);+ for (int32_t i = 0; i < kBlock - kFirst; ++i)+ ok = ok && monitorHwBuf_[i * 2] == static_cast<float>(kFirst + i) && monitorHwBuf_[i * 2 + 1] == -static_cast<float>(kFirst + i);+ while (monitorQueue_.pop(f)) {}+ monitorSharedClock_.store(sharedWas);+ inputBlockFrames_.store(blockWas);+ hwMonitorTap_.store(tapWas);+ monitorPrimed_ = false;+ return ok;+}+void Engine::setTrackMidiSource(int32_t trackId, int32_t sourceTrackId) {if (sourceTrackId == trackId) sourceTrackId = -1; // no self-routingif (auto t = findTrackAuthoring(trackId)) t->setMidiFromTrackId(sourceTrackId);@@ -496,6 +531,9 @@ bool Engine::startAudioRecording(int32_t trackId) {// hardware input. The audio thread feeds the ring from mixGraph; no device is opened.const int32_t src = t->recordInputSource();captureChannels_ = src == 0 ? t->inputChannels() : Track::kInputStereo; // a mono pick is hardware-only+ // A hardware take is late by the device's round trip (in + out); 0 on backends that don't+ // report it, and for internal resampling (specs/049, research R7).+ audioRecordLatencyFrames_ = src == 0 ? audioInputLatencyFrames() + audioOutputLatencyFrames() : 0;if (src != 0) {internalRecordSource_.store(src, std::memory_order_relaxed);audioRecordSampleRate_ = transport_.sampleRate();@@ -622,9 +660,19 @@ void Engine::stopAudioRecording() {return; // loop armed but nothing captured}} else {- clip.startBeat = audioRecordStartBeat_;+ // Linear take: move it earlier by the device latency so it lines up with what was+ // playing when it was performed. (Loop and session takes keep their grid as before.)+ double trimDevice = 0.0;+ clip.startBeat = latencyCompensatedStart(audioRecordStartBeat_, audioRecordLatencyFrames_, spb, &trimDevice);+ double kept = static_cast<double>(sample->frames);+ if (trimDevice > 0.0 && devSR > 0.0) {+ const double trim = std::min(kept, trimDevice * sampleSR / devSR);+ clip.sourceOffsetFrames = trim;+ kept -= trim;+ clip.lengthFrames = static_cast<int64_t>(kept);+ }ns = clip.startBeat;- ne = clip.startBeat + static_cast<double>(sample->frames) * beatsPerFrame;+ ne = clip.startBeat + kept * beatsPerFrame;}if (ne <= ns) return;overwriteAudioClipsInRange(nt->clips, ns, ne);@@ -632,6 +680,16 @@ void Engine::stopAudioRecording() {republishWithTrack(trackId, nt);}+double Engine::latencyCompensatedStart(double startBeat, int32_t latencyFrames, double samplesPerBeat,+ double* trimFrames) {+ if (trimFrames) *trimFrames = 0.0;+ if (latencyFrames <= 0 || samplesPerBeat <= 0.0) return startBeat;+ const double shift = latencyFrames / samplesPerBeat;+ if (startBeat >= shift) return startBeat - shift;+ if (trimFrames) *trimFrames = (shift - std::max(0.0, startBeat)) * samplesPerBeat;+ return 0.0;+}+int32_t Engine::audioRecordPeaks(float* outMinMax, int32_t maxPoints) const {if (!outMinMax || maxPoints <= 0 || !audioRecording_) return 0;const int64_t total = static_cast<int64_t>(audioCaptureBuf_.size() / 2); // frames@@ -669,6 +727,7 @@ bool Engine::audioRecordSelfTest() {audioRecordTrackId_ = tid;audioRecordStartBeat_ = 0.0;audioRecordSampleRate_ = 44100.0;+ audioRecordLatencyFrames_ = 0;audioRecording_ = true; // simulate a take without opening a deviceconstexpr int32_t kFrames = 4410; // 0.1 s@@ -705,6 +764,7 @@ bool Engine::sessionAudioRecordSelfTest() {audioRecordTrackId_ = tid;audioRecordStartBeat_ = 0.0;audioRecordSampleRate_ = 44100.0;+ audioRecordLatencyFrames_ = 0;audioRecording_ = true;constexpr int32_t kFrames = 4410; // 0.1 sdiff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cppindex c4d905bc..6a955249 100644--- a/src/native/nota.engine/src/engine/Engine_Render.cpp+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp@@ -773,8 +773,15 @@ void Engine::closeCtlRange(MidiClip& clip, int32_t ctl, double atLocal, double s// --- audio thread ----------------------------------------------------------void Engine::render(float* out, int32_t numFrames) {+ // Counted before the suspend check (both seq_cst, paired with start()): once start() has+ // suspended rendering and seen the count at zero, no render can be inside the graph.+ rendersInFlight_.fetch_add(1, std::memory_order_seq_cst);+ struct Leave {+ std::atomic<int32_t>& n;+ ~Leave() { n.fetch_sub(1, std::memory_order_release); }+ } leave{rendersInFlight_};// start() is still re-preparing the nodes on the control thread: output silence.- if (renderSuspended_.load(std::memory_order_acquire)) {+ if (renderSuspended_.load(std::memory_order_seq_cst)) {std::fill(out, out + static_cast<size_t>(numFrames) * 2, 0.0f);return;}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 8c7075fb..aceb210f 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -9572,6 +9572,43 @@ Console.WriteLine("-- M7-1: audio device settings --");Check(engine.NegotiatedSampleRate == 0, "negotiated rate is 0 before the backend starts");}+// ===================== specs/049: ASIO on Windows ===========================+// Device-free: the ASIO core runs on a fake driver on every platform (formats, pair+// routing + silence, duplex order, resets, failures, latency compensation, audio.json+// keys). The C ABI must be a safe no-op where the build has no ASIO.+Console.WriteLine("-- specs/049: ASIO --");+{+ Check(NotaEngine.AsioSelfTest(), "ASIO self-test (fake driver): formats, pair routing, duplex, reset, fallback, latency");+ Check(engine.ActiveAudioSystem == AudioSystem.Wasapi, "the engine starts on the native audio system");+ Check(engine.InputLatencyFrames == 0 && engine.OutputLatencyFrames == 0, "no device latency before the backend starts");+ Check(engine.PollDeviceEvent() == AudioDeviceEvent.None, "no device event without a driver");+ Check(engine.AudioFallbackReason == "", "no fallback reason without an ASIO start");+ Check(engine.AsioChannels(false).Count == 0 && engine.AsioChannels(true).Count == 0, "no ASIO channels while ASIO isn't running");+ Check(!engine.OpenAsioControlPanel(), "no driver panel while ASIO isn't running");+ if (!engine.AsioAvailable)+ {+ Check(engine.AsioDrivers().Count == 0, "no ASIO drivers off Windows");+ engine.SetAudioSystem(AudioSystem.Asio);+ engine.SetAsioDriver("{00000000-0000-0000-0000-000000000000}");+ engine.SetAsioPair(false, 2);+ Check(engine.AudioSystem == AudioSystem.Wasapi && engine.AsioDriver == "" && engine.AsioPair(false) == 0,+ "ASIO setters change nothing off Windows");+ }+ else+ {+ // Staging only (no apply): the real backend and audio.json stay untouched.+ engine.SetAudioSystem(AudioSystem.Asio);+ engine.SetAsioPair(false, 2);+ engine.SetAsioPair(true, 4);+ Check(engine.AudioSystem == AudioSystem.Asio && engine.AsioPair(false) == 2 && engine.AsioPair(true) == 4,+ "staged ASIO system and pairs round-trip");+ engine.SetAudioSystem(AudioSystem.Wasapi);+ engine.SetAsioPair(false, 0);+ engine.SetAsioPair(true, 0);+ Console.WriteLine($" [INFO] {engine.AsioDrivers().Count} ASIO driver(s) installed");+ }+}+// ===================== M7-2: MIDI device settings ==========================// Device-free: enumeration + enable/disable staging round-trip. We do NOT call// ApplyMidi() (it writes midi.json and would clobber the user's file); the