pax_global_header00006660000000000000000000000064141007660730014516gustar00rootroot0000000000000052 comment=5e8d273e27d3ebc940566fe68022681914738d1b pcaudiolib-1.2/000077500000000000000000000000001410076607300134735ustar00rootroot00000000000000pcaudiolib-1.2/.gitignore000066400000000000000000000006031410076607300154620ustar00rootroot00000000000000# build artefacts: *.o *.lo # vi/vim editor files: *~ .*.swp # build output: src/libpcaudio.a src/libpcaudio.la pcaudiolib-* # autotools output: Makefile Makefile.in m4/ .libs/ .deps/ .dirstamp README NEWS INSTALL aclocal.m4 autom4te.cache/ ChangeLog compile config.h config.h.in config.h.in~ config.log config.* configure depcomp install-sh missing stamp-h1 libtool ltmain.sh pcaudiolib-1.2/.gitmodules000066400000000000000000000000001410076607300156360ustar00rootroot00000000000000pcaudiolib-1.2/AUTHORS000066400000000000000000000000161410076607300145400ustar00rootroot00000000000000Reece H. Dunn pcaudiolib-1.2/CHANGELOG.md000066400000000000000000000007371410076607300153130ustar00rootroot00000000000000# Change Log ## 1.1 - \[27 Feb 2018\] * Fix handling EBADFD, EPIPE and short write when writing to the ALSA device. * Fix audio echos when using `snd_pcm_drop` in ALSA devices. * Experimental support for Mac OS CoreAudio. ## 1.0 \[10 Sep 2016\] * Provide a consistent API for accessing the different audio interfaces. * Support for PulseAudio using the simple API. * Support for ALSA. * Support for OSS version 3 and later. * Support for QSA. * Support for XAudio2. pcaudiolib-1.2/COPYING000066400000000000000000001045131410076607300145320ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . pcaudiolib-1.2/Makefile.am000066400000000000000000000036651410076607300155410ustar00rootroot00000000000000AUTOMAKE_OPTIONS = subdir-objects localedir = $(datadir)/locale AM_CFLAGS = \ -Isrc/include ACLOCAL_AMFLAGS = -I m4 lib_LTLIBRARIES = EXTRA_DIST = CLEANFILES = ############################# libtool ######################################### EXTRA_DIST += config.guess config.sub ltmain.sh # Increment if the interface has changed and is not backward compatible CURRENT=0 # Increment if source files have changed # Reset to 0 if the interface has changed REVISION=1 # Increment if the interface is backward compatible (superset) # Reset to 0 if the interface is not backward compatible AGE=0 LIBPCAUDIO_VERSION=$(CURRENT):$(REVISION):$(AGE) ############################# ChangeLog ####################################### ChangeLog: git log > ChangeLog dist-hook: ChangeLog .PHONY: ChangeLog EXTRA_DIST += ChangeLog ############################# libpcaudio ###################################### EXTRA_DIST += \ autogen.sh \ CHANGELOG.md \ README.md libpcaudio_includedir = $(includedir)/pcaudiolib libpcaudio_include_HEADERS = \ src/include/pcaudiolib/audio.h lib_LTLIBRARIES += src/libpcaudio.la src_libpcaudio_la_LDFLAGS = -version-info $(LIBPCAUDIO_VERSION) \ ${ALSA_LIBS} \ ${PULSEAUDIO_LIBS} \ ${QSA_LIBS} \ ${COREAUDIO_LIBS} src_libpcaudio_la_CFLAGS = ${AM_CFLAGS} \ ${ALSA_CFLAGS} \ ${PULSEAUDIO_CFLAGS} \ ${COREAUDIO_CFLAGS} src_libpcaudio_la_SOURCES = \ src/alsa.c \ src/qsa.c \ src/oss.c \ src/pulseaudio.c \ src/audio_priv.h \ src/audio.c # Windows audio support EXTRA_DIST += \ src/windows.c \ src/xaudio2.cpp # Mac OSX audio support if HAVE_COREAUDIO src_libpcaudio_la_SOURCES += \ src/coreaudio.c \ src/TPCircularBuffer/TPCircularBuffer.c \ src/TPCircularBuffer/TPCircularBuffer.h \ src/TPCircularBuffer/TPCircularBuffer+AudioBufferList.c \ src/TPCircularBuffer/TPCircularBuffer+AudioBufferList.h EXTRA_DIST += \ src/TPCircularBuffer/README.markdown \ src/TPCircularBuffer/TPCircularBuffer.podspec endif pcaudiolib-1.2/README.md000066400000000000000000000047321410076607300147600ustar00rootroot00000000000000# Portable C Audio Library 1.1 - [Build Dependencies](#build-dependencies) - [Debian](#debian) - [Mac OS](#mac-os) - [Building](#building) - [Bugs](#bugs) - [License Information](#license-information) ---------- The Portable C Audio Library (pcaudiolib) provides a C API to different audio devices. It supports: | Audio Framework | Operating System | |-----------------|------------------| | ALSA | Linux | | CoreAudio | Mac OS | | OSS | POSIX | | PulseAudio | Linux | | QSA | QNX | | XAudio2 | Windows | See the [CHANGELOG](CHANGELOG.md) for a description of the changes in the various releases. ## Build Dependencies In order to build the project, you need: 1. a functional autotools system (`make`, `autoconf`, `automake`, `libtool` and `pkg-config`); 2. a functional c compiler (e.g. gcc or clang). __NOTE:__ Some of the Windows SDK APIs (e.g. the XAudio2 headers) don't compile with a C compiler, so a C++ compiler is needed to compile them. Optionally, you need: 1. the alsa development libraries to enable alsa audio output; 2. the pulseaudio development library to enable pulseaudio output. ### Debian Core dependencies: | Dependency | Install | |------------|------------------------------------------------------------------| | autotools | `sudo apt-get install make autoconf automake libtool pkg-config` | | c compiler | `sudo apt-get install gcc` | Optional Libraries: | Dependency | Install | |----------------|--------------------------------------------| | alsa | `sudo apt-get install libasound2-dev` | | pulseaudio | `sudo apt-get install libpulse-dev` | ### Mac OS To enable CoreAudio output support you need to have the coreaudio framework on your system. Installing XCode along with the Mac OS SDK is the recommended way of getting it. ## Building This project uses a standard autotools build system with an `autogen.sh` script. You can thus build the project using: ./autogen.sh ./configure --prefix=/usr make and install it using: sudo make install ## Bugs Report bugs to the [pcaudiolib issues](https://github.com/espeak-ng/pcaudiolib/issues) page on GitHub. ## License Information The Portable C Audio Library is released under the [GPL version 3](COPYING) or later license. pcaudiolib-1.2/autogen.sh000077500000000000000000000004761410076607300155030ustar00rootroot00000000000000#!/bin/sh LIBTOOLIZE=`which libtoolize` if ! test -f "$LIBTOOLIZE" ; then # Mac OSX support ... LIBTOOLIZE=`which glibtoolize` fi mkdir -p m4 ln -sf README.md README ln -sf CHANGELOG.md NEWS aclocal -I m4 || exit 1 ${LIBTOOLIZE} || exit 1 autoheader || exit 1 automake --add-missing || exit 1 autoconf || exit 1 pcaudiolib-1.2/configure.ac000066400000000000000000000114351410076607300157650ustar00rootroot00000000000000AC_PREREQ([2.65]) AC_INIT([pcaudiolib], [1.2], [https://github.com/rhdunn/pcaudiolib/issues], [], [https://github.com/rhdunn/pcaudiolib]) AM_INIT_AUTOMAKE() m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES]) AM_SILENT_RULES([yes]) AC_CONFIG_SRCDIR([src]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_HEADERS([config.h]) AC_CANONICAL_HOST dnl ================================================================ dnl Program checks. dnl ================================================================ AC_PROG_CC AC_PROG_MAKE_SET AC_PROG_LIBTOOL dnl ================================================================ dnl PulseAudio checks. dnl ================================================================ AC_ARG_WITH([pulseaudio], [AS_HELP_STRING([--with-pulseaudio], [support for PulseAudio output @<:@default=yes@:>@])], []) AS_IF([test "x$with_pulseaudio" = "xno"], [ echo "Disabling PulseAudio output support"; have_pulseaudio=no ], [ PKG_CHECK_MODULES(PULSEAUDIO, [libpulse-simple >= 0.9], [ AC_DEFINE(HAVE_PULSE_SIMPLE_H, [], [Do we have pulse/simple.h]) have_pulseaudio=yes ],[ have_pulseaudio=no ]) ]) AC_SUBST(PULSEAUDIO_CFLAGS) AC_SUBST(PULSEAUDIO_LIBS) dnl ================================================================ dnl ALSA checks. dnl ================================================================ AC_ARG_WITH([alsa], [AS_HELP_STRING([--with-alsa], [support for ALSA audio output @<:@default=yes@:>@])], []) AS_IF([test "x$with_alsa" = "xno"], [ echo "Disabling ALSA audio output support"; have_alsa=no ], [ PKG_CHECK_MODULES(ALSA, [alsa], [ AC_DEFINE(HAVE_ALSA_ASOUNDLIB_H, [], [Do we have ALSA]) have_alsa=yes ],[ have_alsa=no ])]) AC_SUBST(ALSA_CFLAGS) AC_SUBST(ALSA_LIBS) dnl ================================================================ dnl QSA checks. dnl ================================================================ AC_ARG_WITH([qsa], [AS_HELP_STRING([--with-qsa], [support for QSA audio output @<:@default=yes@:>@])], []) if test "$with_qsa" = "no"; then echo "Disabling QSA audio output support" have_qsa=no else AC_CHECK_HEADERS([sys/asoundlib.h],[ AC_CHECK_HEADERS([sys/asound.h],[ have_qsa=yes QSA_LIBS=-lasound ],[ have_qsa=no ]) ],[ have_qsa=no ]) fi AC_SUBST(QSA_LIBS) dnl ================================================================ dnl coreaudio checks. dnl ================================================================ AC_ARG_WITH([coreaudio], [AS_HELP_STRING([--with-coreaudio], [support for coreaudio audio output on Mac OS @<:@default=yes@:>@])], []) if test "$with_coreaudio" = "no";then echo "Disabling coreaudio audio output support" have_coreaudio=no else case $host_os in *darwin*) COREAUDIO_CFLAGS="-dynamiclib -fvisibility=default" COREAUDIO_LIBS="-framework CoreAudio -framework AudioToolbox -framework AudioUnit" have_coreaudio=yes AC_DEFINE(HAVE_COREAUDIO_H, [], [Do we have coreaudio?]) ;; *) have_coreaudio=no ;; esac fi AC_SUBST(COREAUDIO_CFLAGS) AC_SUBST(COREAUDIO_LIBS) AM_CONDITIONAL([HAVE_COREAUDIO], [test "x${have_coreaudio}" = "xyes"]) dnl ================================================================ dnl OSS checks. dnl ================================================================ AC_ARG_WITH([oss], [AS_HELP_STRING([--with-oss], [support for OSS audio output @<:@default=yes@:>@])], []) if test "$with_oss" = "no"; then echo "Disabling OSS audio output support" have_oss=no else AC_CHECK_HEADERS([sys/soundcard.h],[ AC_CHECK_LIB(ossaudio, _oss_ioctl) have_oss=yes ],[ AC_CHECK_HEADERS([linux/soundcard.h],[ AC_CHECK_LIB(ossaudio, _oss_ioctl) have_oss=yes ],[ AC_CHECK_HEADERS([soundcard.h],[ AC_CHECK_LIB(ossaudio, _oss_ioctl) have_oss=yes ],[ have_oss=no ]) ]) ]) fi dnl ================================================================ dnl Generate output. dnl ================================================================ AC_CONFIG_FILES([Makefile]) AC_OUTPUT AC_MSG_NOTICE([ Configuration for Portable C Audio Library complete. Source code location: ${srcdir} Compiler: ${CC} Compiler flags: ${CFLAGS} PulseAudio support: ${have_pulseaudio} ALSA support: ${have_alsa} QSA support: ${have_qsa} Coreaudio support: ${have_coreaudio} OSS support: ${have_oss} ]) pcaudiolib-1.2/src/000077500000000000000000000000001410076607300142625ustar00rootroot00000000000000pcaudiolib-1.2/src/TPCircularBuffer/000077500000000000000000000000001410076607300174245ustar00rootroot00000000000000pcaudiolib-1.2/src/TPCircularBuffer/README.markdown000066400000000000000000000053511410076607300221310ustar00rootroot00000000000000A simple, fast circular buffer implementation for audio processing ================================================================== A simple C implementation for a circular (ring) buffer. Thread-safe with a single producer and a single consumer, using OSAtomic.h primitives, and avoids any need for buffer wrapping logic by using a virtual memory map technique to place a virtual copy of the buffer straight after the end of the real buffer. Usage ----- Initialisation and cleanup: `TPCircularBufferInit` and `TPCircularBufferCleanup` to allocate and free resources. Producing: Use `TPCircularBufferHead` to get a pointer to write to the buffer, followed by `TPCircularBufferProduce` to submit the written data. `TPCircularBufferProduceBytes` is a convenience routine for writing data straight to the buffer. Consuming: Use `TPCircularBufferTail` to get a pointer to the next data to read, followed by `TPCircularBufferConsume` to free up the space once processed. TPCircularBuffer+AudioBufferList.(c,h) contain helper functions to queue and dequeue AudioBufferList structures. These will automatically adjust the mData fields of each buffer to point to 16-byte aligned regions within the circular buffer. Thread safety ------------- As long as you restrict multithreaded access to just one producer, and just one consumer, this utility should be thread safe. Only one shared variable is used (the buffer fill count), and OSAtomic primitives are used to write to this value to ensure atomicity. License ------- Copyright (C) 2012-2013 A Tasty Pixel This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------- Virtual memory technique originally proposed by [Philip Howard](http://vrb.slashusr.org/), and [adapted to Darwin](http://www.snoize.com/Code/PlayBufferedSoundFile.tar.gz) by [Kurt Revis](http://www.snoize.com) See more info at [atastypixel.com](http://atastypixel.com/blog/a-simple-fast-circular-buffer-implementation-for-audio-processing/) pcaudiolib-1.2/src/TPCircularBuffer/TPCircularBuffer+AudioBufferList.c000066400000000000000000000335361410076607300257670ustar00rootroot00000000000000// // TPCircularBuffer+AudioBufferList.c // Circular/Ring buffer implementation // // https://github.com/michaeltyson/TPCircularBuffer // // Created by Michael Tyson on 20/03/2012. // // Copyright (C) 2012-2013 A Tasty Pixel // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // #include "TPCircularBuffer+AudioBufferList.h" #import static double __secondsToHostTicks = 0.0; static inline long align16byte(long val) { if ( val & (16-1) ) { return val + (16 - (val & (16-1))); } return val; } static inline long min(long a, long b) { return a > b ? b : a; } AudioBufferList *TPCircularBufferPrepareEmptyAudioBufferList(TPCircularBuffer *buffer, int numberOfBuffers, int bytesPerBuffer, const AudioTimeStamp *inTimestamp) { int32_t availableBytes; TPCircularBufferABLBlockHeader *block = (TPCircularBufferABLBlockHeader*)TPCircularBufferHead(buffer, &availableBytes); if ( !block || availableBytes < sizeof(TPCircularBufferABLBlockHeader)+((numberOfBuffers-1)*sizeof(AudioBuffer))+(numberOfBuffers*bytesPerBuffer) ) return NULL; #ifdef DEBUG assert(!((unsigned long)block & 0xF) /* Beware unaligned accesses */); #endif if ( inTimestamp ) { memcpy(&block->timestamp, inTimestamp, sizeof(AudioTimeStamp)); } else { memset(&block->timestamp, 0, sizeof(AudioTimeStamp)); } memset(&block->bufferList, 0, sizeof(AudioBufferList)+((numberOfBuffers-1)*sizeof(AudioBuffer))); block->bufferList.mNumberBuffers = numberOfBuffers; char *dataPtr = (char*)&block->bufferList + sizeof(AudioBufferList)+((numberOfBuffers-1)*sizeof(AudioBuffer)); for ( int i=0; i availableBytes ) { return NULL; } block->bufferList.mBuffers[i].mData = dataPtr; block->bufferList.mBuffers[i].mDataByteSize = bytesPerBuffer; block->bufferList.mBuffers[i].mNumberChannels = 1; dataPtr += bytesPerBuffer; } // Make sure whole buffer (including timestamp and length value) is 16-byte aligned in length block->totalLength = (UInt32)align16byte(dataPtr - (char*)block); if ( block->totalLength > availableBytes ) { return NULL; } return &block->bufferList; } AudioBufferList *TPCircularBufferPrepareEmptyAudioBufferListWithAudioFormat(TPCircularBuffer *buffer, const AudioStreamBasicDescription *audioFormat, UInt32 frameCount, const AudioTimeStamp *timestamp) { return TPCircularBufferPrepareEmptyAudioBufferList(buffer, (audioFormat->mFormatFlags & kAudioFormatFlagIsNonInterleaved) ? audioFormat->mChannelsPerFrame : 1, audioFormat->mBytesPerFrame * frameCount, timestamp); } void TPCircularBufferProduceAudioBufferList(TPCircularBuffer *buffer, const AudioTimeStamp *inTimestamp) { int32_t availableBytes; TPCircularBufferABLBlockHeader *block = (TPCircularBufferABLBlockHeader*)TPCircularBufferHead(buffer, &availableBytes); assert(block); #ifdef DEBUG assert(!((unsigned long)block & 0xF) /* Beware unaligned accesses */); #endif assert(block->bufferList.mBuffers[0].mDataByteSize > 0); if ( inTimestamp ) { memcpy(&block->timestamp, inTimestamp, sizeof(AudioTimeStamp)); } UInt32 calculatedLength = (UInt32)(((char*)block->bufferList.mBuffers[block->bufferList.mNumberBuffers-1].mData + block->bufferList.mBuffers[block->bufferList.mNumberBuffers-1].mDataByteSize) - (char*)block); // Make sure whole buffer (including timestamp and length value) is 16-byte aligned in length calculatedLength = (UInt32)align16byte(calculatedLength); assert(calculatedLength <= block->totalLength && calculatedLength <= availableBytes); block->totalLength = calculatedLength; TPCircularBufferProduce(buffer, block->totalLength); } bool TPCircularBufferCopyAudioBufferList(TPCircularBuffer *buffer, const AudioBufferList *inBufferList, const AudioTimeStamp *inTimestamp, UInt32 frames, const AudioStreamBasicDescription *audioDescription) { if ( frames == 0 ) return true; int byteCount = inBufferList->mBuffers[0].mDataByteSize; if ( frames != kTPCircularBufferCopyAll ) { byteCount = frames * audioDescription->mBytesPerFrame; assert(byteCount <= inBufferList->mBuffers[0].mDataByteSize); } if ( byteCount == 0 ) return true; AudioBufferList *bufferList = TPCircularBufferPrepareEmptyAudioBufferList(buffer, inBufferList->mNumberBuffers, byteCount, inTimestamp); if ( !bufferList ) return false; for ( int i=0; imNumberBuffers; i++ ) { memcpy(bufferList->mBuffers[i].mData, inBufferList->mBuffers[i].mData, byteCount); } TPCircularBufferProduceAudioBufferList(buffer, NULL); return true; } AudioBufferList *TPCircularBufferNextBufferListAfter(TPCircularBuffer *buffer, const AudioBufferList *bufferList, AudioTimeStamp *outTimestamp) { int32_t availableBytes; void *tail = TPCircularBufferTail(buffer, &availableBytes); void *end = (char*)tail + availableBytes; assert((void*)bufferList > (void*)tail && (void*)bufferList < end); TPCircularBufferABLBlockHeader *originalBlock = (TPCircularBufferABLBlockHeader*)((char*)bufferList - offsetof(TPCircularBufferABLBlockHeader, bufferList)); #ifdef DEBUG assert(!((unsigned long)originalBlock & 0xF) /* Beware unaligned accesses */); #endif TPCircularBufferABLBlockHeader *nextBlock = (TPCircularBufferABLBlockHeader*)((char*)originalBlock + originalBlock->totalLength); if ( (void*)nextBlock >= end ) return NULL; #ifdef DEBUG assert(!((unsigned long)nextBlock & 0xF) /* Beware unaligned accesses */); #endif if ( outTimestamp ) { memcpy(outTimestamp, &nextBlock->timestamp, sizeof(AudioTimeStamp)); } return &nextBlock->bufferList; } void TPCircularBufferConsumeNextBufferListPartial(TPCircularBuffer *buffer, int framesToConsume, const AudioStreamBasicDescription *audioFormat) { assert(framesToConsume >= 0); int32_t dontcare; TPCircularBufferABLBlockHeader *block = (TPCircularBufferABLBlockHeader*)TPCircularBufferTail(buffer, &dontcare); if ( !block ) return; #ifdef DEBUG assert(!((unsigned long)block & 0xF)); // Beware unaligned accesses #endif int bytesToConsume = (int)min(framesToConsume * audioFormat->mBytesPerFrame, block->bufferList.mBuffers[0].mDataByteSize); if ( bytesToConsume == block->bufferList.mBuffers[0].mDataByteSize ) { TPCircularBufferConsumeNextBufferList(buffer); return; } for ( int i=0; ibufferList.mNumberBuffers; i++ ) { assert(bytesToConsume <= block->bufferList.mBuffers[i].mDataByteSize); block->bufferList.mBuffers[i].mData = (char*)block->bufferList.mBuffers[i].mData + bytesToConsume; block->bufferList.mBuffers[i].mDataByteSize -= bytesToConsume; } if ( block->timestamp.mFlags & kAudioTimeStampSampleTimeValid ) { block->timestamp.mSampleTime += framesToConsume; } if ( block->timestamp.mFlags & kAudioTimeStampHostTimeValid ) { if ( !__secondsToHostTicks ) { mach_timebase_info_data_t tinfo; mach_timebase_info(&tinfo); __secondsToHostTicks = 1.0 / (((double)tinfo.numer / tinfo.denom) * 1.0e-9); } block->timestamp.mHostTime += ((double)framesToConsume / audioFormat->mSampleRate) * __secondsToHostTicks; } // Reposition block forward, just before the audio data, ensuring 16-byte alignment TPCircularBufferABLBlockHeader *newBlock = (TPCircularBufferABLBlockHeader*)(((unsigned long)block + bytesToConsume) & ~0xFul); memmove(newBlock, block, sizeof(TPCircularBufferABLBlockHeader) + (block->bufferList.mNumberBuffers-1)*sizeof(AudioBuffer)); intptr_t bytesFreed = (intptr_t)newBlock - (intptr_t)block; newBlock->totalLength -= bytesFreed; TPCircularBufferConsume(buffer, (int32_t)bytesFreed); } void TPCircularBufferDequeueBufferListFrames(TPCircularBuffer *buffer, UInt32 *ioLengthInFrames, const AudioBufferList *outputBufferList, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat) { bool hasTimestamp = false; UInt32 bytesToGo = *ioLengthInFrames * audioFormat->mBytesPerFrame; UInt32 bytesCopied = 0; while ( bytesToGo > 0 ) { AudioBufferList *bufferList = TPCircularBufferNextBufferList(buffer, !hasTimestamp ? outTimestamp : NULL); if ( !bufferList ) break; hasTimestamp = true; long bytesToCopy = min(bytesToGo, bufferList->mBuffers[0].mDataByteSize); if ( outputBufferList ) { for ( int i=0; imNumberBuffers; i++ ) { assert(bytesCopied + bytesToCopy <= outputBufferList->mBuffers[i].mDataByteSize); memcpy((char*)outputBufferList->mBuffers[i].mData + bytesCopied, bufferList->mBuffers[i].mData, bytesToCopy); } } TPCircularBufferConsumeNextBufferListPartial(buffer, (int)bytesToCopy/audioFormat->mBytesPerFrame, audioFormat); bytesToGo -= bytesToCopy; bytesCopied += bytesToCopy; } *ioLengthInFrames -= bytesToGo / audioFormat->mBytesPerFrame; } UInt32 TPCircularBufferPeekContiguousWrapped(TPCircularBuffer *buffer, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat, UInt32 contiguousToleranceSampleTime, UInt32 wrapPoint) { int32_t availableBytes; TPCircularBufferABLBlockHeader *block = (TPCircularBufferABLBlockHeader*)TPCircularBufferTail(buffer, &availableBytes); if ( !block ) return 0; #ifdef DEBUG assert(!((unsigned long)block & 0xF) /* Beware unaligned accesses */); #endif if ( outTimestamp ) { memcpy(outTimestamp, &block->timestamp, sizeof(AudioTimeStamp)); } void *end = (char*)block + availableBytes; UInt32 byteCount = 0; while ( 1 ) { byteCount += block->bufferList.mBuffers[0].mDataByteSize; TPCircularBufferABLBlockHeader *nextBlock = (TPCircularBufferABLBlockHeader*)((char*)block + block->totalLength); if ( (void*)nextBlock >= end ) { break; } if ( contiguousToleranceSampleTime != UINT32_MAX ) { UInt32 frames = block->bufferList.mBuffers[0].mDataByteSize / audioFormat->mBytesPerFrame; Float64 nextTime = block->timestamp.mSampleTime + frames; if ( wrapPoint && nextTime > wrapPoint ) nextTime = fmod(nextTime, wrapPoint); Float64 diff = fabs(nextBlock->timestamp.mSampleTime - nextTime); if ( diff > contiguousToleranceSampleTime && (!wrapPoint || fabs(diff-wrapPoint) > contiguousToleranceSampleTime) ) { break; } } #ifdef DEBUG assert(!((unsigned long)nextBlock & 0xF) /* Beware unaligned accesses */); #endif block = nextBlock; } return byteCount / audioFormat->mBytesPerFrame; } UInt32 TPCircularBufferPeek(TPCircularBuffer *buffer, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat) { return TPCircularBufferPeekContiguousWrapped(buffer, outTimestamp, audioFormat, UINT32_MAX, 0); } UInt32 TPCircularBufferPeekContiguous(TPCircularBuffer *buffer, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat, UInt32 contiguousToleranceSampleTime) { return TPCircularBufferPeekContiguousWrapped(buffer, outTimestamp, audioFormat, contiguousToleranceSampleTime, 0); } UInt32 TPCircularBufferGetAvailableSpace(TPCircularBuffer *buffer, const AudioStreamBasicDescription *audioFormat) { // Look at buffer head; make sure there's space for the block metadata int32_t availableBytes; TPCircularBufferABLBlockHeader *block = (TPCircularBufferABLBlockHeader*)TPCircularBufferHead(buffer, &availableBytes); if ( !block ) return 0; #ifdef DEBUG assert(!((unsigned long)block & 0xF) /* Beware unaligned accesses */); #endif // Now find out how much 16-byte aligned audio we can store in the space available int numberOfBuffers = audioFormat->mFormatFlags & kAudioFormatFlagIsNonInterleaved ? audioFormat->mChannelsPerFrame : 1; char * endOfBuffer = (char*)block + availableBytes; char * dataPtr = (char*)align16byte((long)(&block->bufferList + sizeof(AudioBufferList)+((numberOfBuffers-1)*sizeof(AudioBuffer)))); if ( dataPtr >= endOfBuffer ) return 0; int32_t availableAudioBytes = (int)(endOfBuffer - dataPtr); int32_t availableAudioBytesPerBuffer = availableAudioBytes / numberOfBuffers; availableAudioBytesPerBuffer -= (availableAudioBytesPerBuffer % (16-1)); return availableAudioBytesPerBuffer > 0 ? availableAudioBytesPerBuffer / audioFormat->mBytesPerFrame : 0; } pcaudiolib-1.2/src/TPCircularBuffer/TPCircularBuffer+AudioBufferList.h000066400000000000000000000261571410076607300257750ustar00rootroot00000000000000// // TPCircularBuffer+AudioBufferList.h // Circular/Ring buffer implementation // // https://github.com/michaeltyson/TPCircularBuffer // // Created by Michael Tyson on 20/03/2012. // // Copyright (C) 2012-2013 A Tasty Pixel // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // #ifndef TPCircularBuffer_AudioBufferList_h #define TPCircularBuffer_AudioBufferList_h #ifdef __cplusplus extern "C" { #endif #include "TPCircularBuffer.h" #include #define kTPCircularBufferCopyAll UINT32_MAX typedef struct { AudioTimeStamp timestamp; UInt32 totalLength; AudioBufferList bufferList; } TPCircularBufferABLBlockHeader; /*! * Prepare an empty buffer list, stored on the circular buffer * * @param buffer Circular buffer * @param numberOfBuffers The number of buffers to be contained within the buffer list * @param bytesPerBuffer The number of bytes to store for each buffer * @param timestamp The timestamp associated with the buffer, or NULL. Note that you can also pass a timestamp into TPCircularBufferProduceAudioBufferList, to set it there instead. * @return The empty buffer list, or NULL if circular buffer has insufficient space */ AudioBufferList *TPCircularBufferPrepareEmptyAudioBufferList(TPCircularBuffer *buffer, int numberOfBuffers, int bytesPerBuffer, const AudioTimeStamp *timestamp); /*! * Prepare an empty buffer list, stored on the circular buffer, using an audio description to automatically configure buffer * * @param buffer Circular buffer * @param audioFormat The kind of audio that will be stored * @param frameCount The number of frames that will be stored * @param timestamp The timestamp associated with the buffer, or NULL. Note that you can also pass a timestamp into TPCircularBufferProduceAudioBufferList, to set it there instead. * @return The empty buffer list, or NULL if circular buffer has insufficient space */ AudioBufferList *TPCircularBufferPrepareEmptyAudioBufferListWithAudioFormat(TPCircularBuffer *buffer, const AudioStreamBasicDescription *audioFormat, UInt32 frameCount, const AudioTimeStamp *timestamp); /*! * Mark next audio buffer list as ready for reading * * This marks the audio buffer list prepared using TPCircularBufferPrepareEmptyAudioBufferList * as ready for reading. You must not call this function without first calling * TPCircularBufferPrepareEmptyAudioBufferList. * * @param buffer Circular buffer * @param inTimestamp The timestamp associated with the buffer, or NULL to leave as-is. Note that you can also pass a timestamp into TPCircularBufferPrepareEmptyAudioBufferList, to set it there instead. */ void TPCircularBufferProduceAudioBufferList(TPCircularBuffer *buffer, const AudioTimeStamp *inTimestamp); /*! * Copy the audio buffer list onto the buffer * * @param buffer Circular buffer * @param bufferList Buffer list containing audio to copy to buffer * @param timestamp The timestamp associated with the buffer, or NULL * @param frames Length of audio in frames. Specify kTPCircularBufferCopyAll to copy the whole buffer (audioFormat can be NULL, in this case) * @param audioFormat The AudioStreamBasicDescription describing the audio, or NULL if you specify kTPCircularBufferCopyAll to the `frames` argument * @return YES if buffer list was successfully copied; NO if there was insufficient space */ bool TPCircularBufferCopyAudioBufferList(TPCircularBuffer *buffer, const AudioBufferList *bufferList, const AudioTimeStamp *timestamp, UInt32 frames, const AudioStreamBasicDescription *audioFormat); /*! * Get a pointer to the next stored buffer list * * @param buffer Circular buffer * @param outTimestamp On output, if not NULL, the timestamp corresponding to the buffer * @return Pointer to the next buffer list in the buffer */ static __inline__ __attribute__((always_inline)) AudioBufferList *TPCircularBufferNextBufferList(TPCircularBuffer *buffer, AudioTimeStamp *outTimestamp) { int32_t dontcare; // Length of segment is contained within buffer list, so we can ignore this TPCircularBufferABLBlockHeader *block = (TPCircularBufferABLBlockHeader*)TPCircularBufferTail(buffer, &dontcare); if ( !block ) { if ( outTimestamp ) { memset(outTimestamp, 0, sizeof(AudioTimeStamp)); } return NULL; } if ( outTimestamp ) { memcpy(outTimestamp, &block->timestamp, sizeof(AudioTimeStamp)); } return &block->bufferList; } /*! * Get a pointer to the next stored buffer list after the given one * * @param buffer Circular buffer * @param bufferList Preceding buffer list * @param outTimestamp On output, if not NULL, the timestamp corresponding to the buffer * @return Pointer to the next buffer list in the buffer, or NULL */ AudioBufferList *TPCircularBufferNextBufferListAfter(TPCircularBuffer *buffer, const AudioBufferList *bufferList, AudioTimeStamp *outTimestamp); /*! * Consume the next buffer list * * @param buffer Circular buffer */ static __inline__ __attribute__((always_inline)) void TPCircularBufferConsumeNextBufferList(TPCircularBuffer *buffer) { int32_t dontcare; TPCircularBufferABLBlockHeader *block = (TPCircularBufferABLBlockHeader*)TPCircularBufferTail(buffer, &dontcare); if ( !block ) return; TPCircularBufferConsume(buffer, block->totalLength); } /*! * Consume a portion of the next buffer list * * This will also increment the sample time and host time portions of the timestamp of * the buffer list, if present. * * @param buffer Circular buffer * @param framesToConsume The number of frames to consume from the buffer list * @param audioFormat The AudioStreamBasicDescription describing the audio */ void TPCircularBufferConsumeNextBufferListPartial(TPCircularBuffer *buffer, int framesToConsume, const AudioStreamBasicDescription *audioFormat); /*! * Consume a certain number of frames from the buffer, possibly from multiple queued buffer lists * * Copies the given number of frames from the buffer into outputBufferList, of the * given audio description, then consumes the audio buffers. If an audio buffer has * not been entirely consumed, then updates the queued buffer list structure to point * to the unconsumed data only. * * @param buffer Circular buffer * @param ioLengthInFrames On input, the number of frames in the given audio format to consume; on output, the number of frames provided * @param outputBufferList The buffer list to copy audio to, or NULL to discard audio. If not NULL, the structure must be initialised properly, and the mData pointers must not be NULL. * @param outTimestamp On output, if not NULL, the timestamp corresponding to the first audio frame returned * @param audioFormat The format of the audio stored in the buffer */ void TPCircularBufferDequeueBufferListFrames(TPCircularBuffer *buffer, UInt32 *ioLengthInFrames, const AudioBufferList *outputBufferList, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat); /*! * Determine how many frames of audio are buffered * * Given the provided audio format, determines the frame count of all queued buffers * * Note: This function should only be used on the consumer thread, not the producer thread. * * @param buffer Circular buffer * @param outTimestamp On output, if not NULL, the timestamp corresponding to the first audio frame * @param audioFormat The format of the audio stored in the buffer * @return The number of frames in the given audio format that are in the buffer */ UInt32 TPCircularBufferPeek(TPCircularBuffer *buffer, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat); /*! * Determine how many contiguous frames of audio are buffered * * Given the provided audio format, determines the frame count of all queued buffers that are contiguous, * given their corresponding timestamps (sample time). * * Note: This function should only be used on the consumer thread, not the producer thread. * * @param buffer Circular buffer * @param outTimestamp On output, if not NULL, the timestamp corresponding to the first audio frame * @param audioFormat The format of the audio stored in the buffer * @param contiguousToleranceSampleTime The number of samples of discrepancy to tolerate * @return The number of frames in the given audio format that are in the buffer */ UInt32 TPCircularBufferPeekContiguous(TPCircularBuffer *buffer, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat, UInt32 contiguousToleranceSampleTime); /*! * Determine how many contiguous frames of audio are buffered, with wrap around * * Like TPCircularBufferPeekContiguous, determines how many contiguous frames are buffered, * but considers audio that wraps around a region of a given length as also contiguous. This * is good for audio that loops. * * Note: This function should only be used on the consumer thread, not the producer thread. * * @param buffer Circular buffer * @param outTimestamp On output, if not NULL, the timestamp corresponding to the first audio frame * @param audioFormat The format of the audio stored in the buffer * @param contiguousToleranceSampleTime The number of samples of discrepancy to tolerate * @param wrapPoint The point around which the audio may wrap and still be considered contiguous, or 0 to disable * @return The number of frames in the given audio format that are in the buffer */ UInt32 TPCircularBufferPeekContiguousWrapped(TPCircularBuffer *buffer, AudioTimeStamp *outTimestamp, const AudioStreamBasicDescription *audioFormat, UInt32 contiguousToleranceSampleTime, UInt32 wrapPoint); /*! * Determine how many much space there is in the buffer * * Given the provided audio format, determines the number of frames of audio that can be buffered. * * Note: This function should only be used on the producer thread, not the consumer thread. * * @param buffer Circular buffer * @param audioFormat The format of the audio stored in the buffer * @return The number of frames in the given audio format that can be stored in the buffer */ UInt32 TPCircularBufferGetAvailableSpace(TPCircularBuffer *buffer, const AudioStreamBasicDescription *audioFormat); #ifdef __cplusplus } #endif #endif pcaudiolib-1.2/src/TPCircularBuffer/TPCircularBuffer.c000066400000000000000000000135531410076607300227410ustar00rootroot00000000000000// // TPCircularBuffer.c // Circular/Ring buffer implementation // // https://github.com/michaeltyson/TPCircularBuffer // // Created by Michael Tyson on 10/12/2011. // // Copyright (C) 2012-2013 A Tasty Pixel // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // #include "TPCircularBuffer.h" #include #include #include #define reportResult(result,operation) (_reportResult((result),(operation),strrchr(__FILE__, '/')+1,__LINE__)) static inline bool _reportResult(kern_return_t result, const char *operation, const char* file, int line) { if ( result != ERR_SUCCESS ) { printf("%s:%d: %s: %s\n", file, line, operation, mach_error_string(result)); return false; } return true; } bool _TPCircularBufferInit(TPCircularBuffer *buffer, int32_t length, size_t structSize) { assert(length > 0); if ( structSize != sizeof(TPCircularBuffer) ) { fprintf(stderr, "TPCircularBuffer: Header version mismatch. Check for old versions of TPCircularBuffer in your project\n"); abort(); } // Keep trying until we get our buffer, needed to handle race conditions int retries = 3; while ( true ) { buffer->length = (int32_t)round_page(length); // We need whole page sizes // Temporarily allocate twice the length, so we have the contiguous address space to // support a second instance of the buffer directly after vm_address_t bufferAddress; kern_return_t result = vm_allocate(mach_task_self(), &bufferAddress, buffer->length * 2, VM_FLAGS_ANYWHERE); // allocate anywhere it'll fit if ( result != ERR_SUCCESS ) { if ( retries-- == 0 ) { reportResult(result, "Buffer allocation"); return false; } // Try again if we fail continue; } // Now replace the second half of the allocation with a virtual copy of the first half. Deallocate the second half... result = vm_deallocate(mach_task_self(), bufferAddress + buffer->length, buffer->length); if ( result != ERR_SUCCESS ) { if ( retries-- == 0 ) { reportResult(result, "Buffer deallocation"); return false; } // If this fails somehow, deallocate the whole region and try again vm_deallocate(mach_task_self(), bufferAddress, buffer->length); continue; } // Re-map the buffer to the address space immediately after the buffer vm_address_t virtualAddress = bufferAddress + buffer->length; vm_prot_t cur_prot, max_prot; result = vm_remap(mach_task_self(), &virtualAddress, // mirror target buffer->length, // size of mirror 0, // auto alignment 0, // force remapping to virtualAddress mach_task_self(), // same task bufferAddress, // mirror source 0, // MAP READ-WRITE, NOT COPY &cur_prot, // unused protection struct &max_prot, // unused protection struct VM_INHERIT_DEFAULT); if ( result != ERR_SUCCESS ) { if ( retries-- == 0 ) { reportResult(result, "Remap buffer memory"); return false; } // If this remap failed, we hit a race condition, so deallocate and try again vm_deallocate(mach_task_self(), bufferAddress, buffer->length); continue; } if ( virtualAddress != bufferAddress+buffer->length ) { // If the memory is not contiguous, clean up both allocated buffers and try again if ( retries-- == 0 ) { printf("Couldn't map buffer memory to end of buffer\n"); return false; } vm_deallocate(mach_task_self(), virtualAddress, buffer->length); vm_deallocate(mach_task_self(), bufferAddress, buffer->length); continue; } buffer->buffer = (void*)bufferAddress; buffer->fillCount = 0; buffer->head = buffer->tail = 0; buffer->atomic = true; return true; } return false; } void TPCircularBufferCleanup(TPCircularBuffer *buffer) { vm_deallocate(mach_task_self(), (vm_address_t)buffer->buffer, buffer->length * 2); memset(buffer, 0, sizeof(TPCircularBuffer)); } void TPCircularBufferClear(TPCircularBuffer *buffer) { int32_t fillCount; if ( TPCircularBufferTail(buffer, &fillCount) ) { TPCircularBufferConsume(buffer, fillCount); } } void TPCircularBufferSetAtomic(TPCircularBuffer *buffer, bool atomic) { buffer->atomic = atomic; } pcaudiolib-1.2/src/TPCircularBuffer/TPCircularBuffer.h000066400000000000000000000174371410076607300227530ustar00rootroot00000000000000// // TPCircularBuffer.h // Circular/Ring buffer implementation // // https://github.com/michaeltyson/TPCircularBuffer // // Created by Michael Tyson on 10/12/2011. // // // This implementation makes use of a virtual memory mapping technique that inserts a virtual copy // of the buffer memory directly after the buffer's end, negating the need for any buffer wrap-around // logic. Clients can simply use the returned memory address as if it were contiguous space. // // The implementation is thread-safe in the case of a single producer and single consumer. // // Virtual memory technique originally proposed by Philip Howard (http://vrb.slashusr.org/), and // adapted to Darwin by Kurt Revis (http://www.snoize.com, // http://www.snoize.com/Code/PlayBufferedSoundFile.tar.gz) // // // Copyright (C) 2012-2013 A Tasty Pixel // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // #ifndef TPCircularBuffer_h #define TPCircularBuffer_h #include #include #include #ifdef __cplusplus extern "C++" { #include using namespace std; } #else #include #endif #ifdef __cplusplus extern "C" { #endif typedef struct { void *buffer; int32_t length; int32_t tail; int32_t head; volatile atomic_int fillCount; bool atomic; } TPCircularBuffer; /*! * Initialise buffer * * Note that the length is advisory only: Because of the way the * memory mirroring technique works, the true buffer length will * be multiples of the device page size (e.g. 4096 bytes) * * If you intend to use the AudioBufferList utilities, you should * always allocate a bit more space than you need for pure audio * data, so there's room for the metadata. How much extra is required * depends on how many AudioBufferList structures are used, which is * a function of how many audio frames each buffer holds. A good rule * of thumb is to add 15%, or at least another 2048 bytes or so. * * @param buffer Circular buffer * @param length Length of buffer */ #define TPCircularBufferInit(buffer, length) \ _TPCircularBufferInit(buffer, length, sizeof(*buffer)) bool _TPCircularBufferInit(TPCircularBuffer *buffer, int32_t length, size_t structSize); /*! * Cleanup buffer * * Releases buffer resources. */ void TPCircularBufferCleanup(TPCircularBuffer *buffer); /*! * Clear buffer * * Resets buffer to original, empty state. * * This is safe for use by consumer while producer is accessing * buffer. */ void TPCircularBufferClear(TPCircularBuffer *buffer); /*! * Set the atomicity * * If you set the atomiticy to false using this method, the buffer will * not use atomic operations. This can be used to give the compiler a little * more optimisation opportunities when the buffer is only used on one thread. * * Important note: Only set this to false if you know what you're doing! * * The default value is true (the buffer will use atomic operations) * * @param buffer Circular buffer * @param atomic Whether the buffer is atomic (default true) */ void TPCircularBufferSetAtomic(TPCircularBuffer *buffer, bool atomic); // Reading (consuming) /*! * Access end of buffer * * This gives you a pointer to the end of the buffer, ready * for reading, and the number of available bytes to read. * * @param buffer Circular buffer * @param availableBytes On output, the number of bytes ready for reading * @return Pointer to the first bytes ready for reading, or NULL if buffer is empty */ static __inline__ __attribute__((always_inline)) void* TPCircularBufferTail(TPCircularBuffer *buffer, int32_t* availableBytes) { *availableBytes = buffer->fillCount; if ( *availableBytes == 0 ) return NULL; return (void*)((char*)buffer->buffer + buffer->tail); } /*! * Consume bytes in buffer * * This frees up the just-read bytes, ready for writing again. * * @param buffer Circular buffer * @param amount Number of bytes to consume */ static __inline__ __attribute__((always_inline)) void TPCircularBufferConsume(TPCircularBuffer *buffer, int32_t amount) { buffer->tail = (buffer->tail + amount) % buffer->length; if ( buffer->atomic ) { atomic_fetch_add(&buffer->fillCount, -amount); } else { buffer->fillCount -= amount; } assert(buffer->fillCount >= 0); } /*! * Access front of buffer * * This gives you a pointer to the front of the buffer, ready * for writing, and the number of available bytes to write. * * @param buffer Circular buffer * @param availableBytes On output, the number of bytes ready for writing * @return Pointer to the first bytes ready for writing, or NULL if buffer is full */ static __inline__ __attribute__((always_inline)) void* TPCircularBufferHead(TPCircularBuffer *buffer, int32_t* availableBytes) { *availableBytes = (buffer->length - buffer->fillCount); if ( *availableBytes == 0 ) return NULL; return (void*)((char*)buffer->buffer + buffer->head); } // Writing (producing) /*! * Produce bytes in buffer * * This marks the given section of the buffer ready for reading. * * @param buffer Circular buffer * @param amount Number of bytes to produce */ static __inline__ __attribute__((always_inline)) void TPCircularBufferProduce(TPCircularBuffer *buffer, int32_t amount) { buffer->head = (buffer->head + amount) % buffer->length; if ( buffer->atomic ) { atomic_fetch_add(&buffer->fillCount, amount); } else { buffer->fillCount += amount; } assert(buffer->fillCount <= buffer->length); } /*! * Helper routine to copy bytes to buffer * * This copies the given bytes to the buffer, and marks them ready for reading. * * @param buffer Circular buffer * @param src Source buffer * @param len Number of bytes in source buffer * @return true if bytes copied, false if there was insufficient space */ static __inline__ __attribute__((always_inline)) bool TPCircularBufferProduceBytes(TPCircularBuffer *buffer, const void* src, int32_t len) { int32_t space; void *ptr = TPCircularBufferHead(buffer, &space); if ( space < len ) return false; memcpy(ptr, src, len); TPCircularBufferProduce(buffer, len); return true; } /*! * Deprecated method */ static __inline__ __attribute__((always_inline)) __deprecated_msg("use TPCircularBufferSetAtomic(false) and TPCircularBufferConsume instead") void TPCircularBufferConsumeNoBarrier(TPCircularBuffer *buffer, int32_t amount) { buffer->tail = (buffer->tail + amount) % buffer->length; buffer->fillCount -= amount; assert(buffer->fillCount >= 0); } /*! * Deprecated method */ static __inline__ __attribute__((always_inline)) __deprecated_msg("use TPCircularBufferSetAtomic(false) and TPCircularBufferProduce instead") void TPCircularBufferProduceNoBarrier(TPCircularBuffer *buffer, int32_t amount) { buffer->head = (buffer->head + amount) % buffer->length; buffer->fillCount += amount; assert(buffer->fillCount <= buffer->length); } #ifdef __cplusplus } #endif #endif pcaudiolib-1.2/src/TPCircularBuffer/TPCircularBuffer.podspec000066400000000000000000000032601410076607300241460ustar00rootroot00000000000000license = <<-END Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." END Pod::Spec.new do |s| s.name = "TPCircularBuffer" s.version = '1.4' s.summary = 'A simple, fast circular buffer implementation.' s.homepage = 'https://github.com/michaeltyson/TPCircularBuffer' s.authors = { 'Michael Tyson' => 'michael@atastypixel.com' } s.license = { :type => 'MIT', :text => license } s.source = { :git => 'https://github.com/michaeltyson/TPCircularBuffer.git', :tag => '1.4' } s.source_files = '*.{c,h}' s.requires_arc = false s.frameworks = 'AudioToolbox' s.ios.deployment_target = '4.3' s.osx.deployment_target = '10.8' end pcaudiolib-1.2/src/alsa.c000066400000000000000000000210561410076607300153520ustar00rootroot00000000000000/* ALSA Output. * * Copyright (C) 2016 Reece H. Dunn * * This file is part of pcaudiolib. * * pcaudiolib 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. * * pcaudiolib 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 pcaudiolib. If not, see . */ #include "config.h" #include "audio_priv.h" #ifdef HAVE_ALSA_ASOUNDLIB_H #include #include #include struct alsa_object { struct audio_object vtable; snd_pcm_t *handle; uint8_t sample_size; char *device; /* saved audio_object_open parameters */ int is_open; enum audio_object_format format; uint32_t rate; uint8_t channels; }; #define to_alsa_object(object) container_of(object, struct alsa_object, vtable) int alsa_object_open(struct audio_object *object, enum audio_object_format format, uint32_t rate, uint8_t channels) { struct alsa_object *self = to_alsa_object(object); if (self->handle) return -EEXIST; snd_pcm_format_t pcm_format; #define FORMAT(srcfmt, dstfmt, size) case srcfmt: pcm_format = dstfmt; self->sample_size = size*channels; break; switch (format) { FORMAT(AUDIO_OBJECT_FORMAT_ALAW, SND_PCM_FORMAT_A_LAW, 1) FORMAT(AUDIO_OBJECT_FORMAT_ULAW, SND_PCM_FORMAT_MU_LAW, 1) FORMAT(AUDIO_OBJECT_FORMAT_S8, SND_PCM_FORMAT_S8, 1) FORMAT(AUDIO_OBJECT_FORMAT_U8, SND_PCM_FORMAT_U8, 1) FORMAT(AUDIO_OBJECT_FORMAT_S16LE, SND_PCM_FORMAT_S16_LE, 2) FORMAT(AUDIO_OBJECT_FORMAT_S16BE, SND_PCM_FORMAT_S16_BE, 2) FORMAT(AUDIO_OBJECT_FORMAT_U16LE, SND_PCM_FORMAT_U16_LE, 2) FORMAT(AUDIO_OBJECT_FORMAT_U16BE, SND_PCM_FORMAT_U16_BE, 2) FORMAT(AUDIO_OBJECT_FORMAT_S18LE, SND_PCM_FORMAT_S18_3LE, 3) FORMAT(AUDIO_OBJECT_FORMAT_S18BE, SND_PCM_FORMAT_S18_3BE, 3) FORMAT(AUDIO_OBJECT_FORMAT_U18LE, SND_PCM_FORMAT_U18_3LE, 3) FORMAT(AUDIO_OBJECT_FORMAT_U18BE, SND_PCM_FORMAT_U18_3BE, 3) FORMAT(AUDIO_OBJECT_FORMAT_S20LE, SND_PCM_FORMAT_S20_3LE, 3) FORMAT(AUDIO_OBJECT_FORMAT_S20BE, SND_PCM_FORMAT_S20_3BE, 3) FORMAT(AUDIO_OBJECT_FORMAT_U20LE, SND_PCM_FORMAT_U20_3LE, 3) FORMAT(AUDIO_OBJECT_FORMAT_U20BE, SND_PCM_FORMAT_U20_3BE, 3) FORMAT(AUDIO_OBJECT_FORMAT_S24LE, SND_PCM_FORMAT_S24_3LE, 3) FORMAT(AUDIO_OBJECT_FORMAT_S24BE, SND_PCM_FORMAT_S24_3BE, 3) FORMAT(AUDIO_OBJECT_FORMAT_U24LE, SND_PCM_FORMAT_U24_3LE, 3) FORMAT(AUDIO_OBJECT_FORMAT_U24BE, SND_PCM_FORMAT_U24_3BE, 3) FORMAT(AUDIO_OBJECT_FORMAT_S24_32LE, SND_PCM_FORMAT_S24_LE, 4) FORMAT(AUDIO_OBJECT_FORMAT_S24_32BE, SND_PCM_FORMAT_S24_BE, 4) FORMAT(AUDIO_OBJECT_FORMAT_U24_32LE, SND_PCM_FORMAT_U24_LE, 4) FORMAT(AUDIO_OBJECT_FORMAT_U24_32BE, SND_PCM_FORMAT_U24_BE, 4) FORMAT(AUDIO_OBJECT_FORMAT_S32LE, SND_PCM_FORMAT_S32_LE, 4) FORMAT(AUDIO_OBJECT_FORMAT_S32BE, SND_PCM_FORMAT_S32_BE, 4) FORMAT(AUDIO_OBJECT_FORMAT_U32LE, SND_PCM_FORMAT_U32_LE, 4) FORMAT(AUDIO_OBJECT_FORMAT_U32BE, SND_PCM_FORMAT_U32_BE, 4) FORMAT(AUDIO_OBJECT_FORMAT_FLOAT32LE, SND_PCM_FORMAT_FLOAT_LE, 4) FORMAT(AUDIO_OBJECT_FORMAT_FLOAT32BE, SND_PCM_FORMAT_FLOAT_BE, 4) FORMAT(AUDIO_OBJECT_FORMAT_FLOAT64LE, SND_PCM_FORMAT_FLOAT64_LE, 8) FORMAT(AUDIO_OBJECT_FORMAT_FLOAT64BE, SND_PCM_FORMAT_FLOAT64_BE, 8) FORMAT(AUDIO_OBJECT_FORMAT_IEC958LE, SND_PCM_FORMAT_IEC958_SUBFRAME_LE, 1) FORMAT(AUDIO_OBJECT_FORMAT_IEC958BE, SND_PCM_FORMAT_IEC958_SUBFRAME_BE, 1) FORMAT(AUDIO_OBJECT_FORMAT_ADPCM, SND_PCM_FORMAT_IMA_ADPCM, 1) FORMAT(AUDIO_OBJECT_FORMAT_MPEG, SND_PCM_FORMAT_MPEG, 1) FORMAT(AUDIO_OBJECT_FORMAT_GSM, SND_PCM_FORMAT_GSM, 1) default: return -EINVAL; } #undef FORMAT snd_pcm_hw_params_t *params = NULL; snd_pcm_hw_params_malloc(¶ms); snd_pcm_uframes_t bufsize = (rate * channels * LATENCY) / 1000; int err = 0; if ((err = snd_pcm_open(&self->handle, self->device ? self->device : "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0) goto error; if ((err = snd_pcm_hw_params_any(self->handle, params)) < 0) goto error; if ((err = snd_pcm_hw_params_set_access(self->handle, params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) goto error; if ((err = snd_pcm_hw_params_set_format(self->handle, params, pcm_format)) < 0) goto error; if ((err = snd_pcm_hw_params_set_rate_near(self->handle, params, &rate, 0)) < 0) goto error; if ((err = snd_pcm_hw_params_set_channels(self->handle, params, channels)) < 0) goto error; if ((err = snd_pcm_hw_params_set_buffer_size_near(self->handle, params, &bufsize)) < 0) goto error; if ((err = snd_pcm_hw_params(self->handle, params)) < 0) goto error; if ((err = snd_pcm_prepare(self->handle)) < 0) goto error; self->is_open = 1; self->format = format; self->rate = rate; self->channels = channels; return 0; error: if (params) snd_pcm_hw_params_free(params); if (self->handle) { snd_pcm_close(self->handle); self->handle = NULL; self->is_open = 0; } return err; } void alsa_object_close(struct audio_object *object) { struct alsa_object *self = to_alsa_object(object); if (self->handle) { snd_pcm_close(self->handle); self->handle = NULL; self->is_open = 1; } } void alsa_object_destroy(struct audio_object *object) { struct alsa_object *self = to_alsa_object(object); free(self->device); free(self); } int alsa_object_drain(struct audio_object *object) { struct alsa_object *self = to_alsa_object(object); int ret = 0; if (self->handle) { snd_pcm_drain(self->handle); ret = snd_pcm_prepare(self->handle); } return ret; } int alsa_object_flush(struct audio_object *object) { struct alsa_object *self = to_alsa_object(object); if (!self) return 0; // Using snd_pcm_drop does not discard the audio, so reopen the device // to reset the sound buffer. if (self->is_open) { audio_object_close(object); return audio_object_open(object, self->format, self->rate, self->channels); } return 0; } int alsa_object_write(struct audio_object *object, const void *data, size_t bytes) { struct alsa_object *self = to_alsa_object(object); if (!self->handle) return 0; int err = 0; snd_pcm_uframes_t nToWrite = bytes / self->sample_size; // Number of frames to write. snd_pcm_sframes_t nWritten = 0; // And number alsa actually wrote. while (1) { nWritten = snd_pcm_writei(self->handle, data, nToWrite); if ((nWritten >= 0) && (nWritten < nToWrite)) { // Can happen in case of a signal or underrun. nToWrite -= nWritten; data += nWritten * self->sample_size; // Open question: if a signal caused the short read, should we snd_pcm_prepare? } else if ((nWritten == -EPIPE) #ifdef EBADFD || (nWritten == -EBADFD) #endif ) { // Either there was an underrun or the PCM was in a bad state. err = snd_pcm_prepare(self->handle); if (err != 0) break; } #ifdef ESTRPIPE else if (nWritten == -ESTRPIPE) { // Sound suspended, try to resume. do { err = snd_pcm_resume(self->handle); sleep(1); } while (err == -EAGAIN); if (err == -ENOSYS) { // Hardware doesn't support "fine resume". // So just prepare. err = snd_pcm_prepare(self->handle); } if (err < 0) { break; } } #endif else { err = nWritten; break; } } return err >= 0 ? 0 : err; } const char * alsa_object_strerror(struct audio_object *object, int error) { return snd_strerror(error); } struct audio_object * create_alsa_object(const char *device, const char *application_name, const char *description) { struct alsa_object *self = malloc(sizeof(struct alsa_object)); if (!self) return NULL; self->handle = NULL; self->sample_size = 0; self->device = device ? strdup(device) : NULL; self->is_open = 0; self->vtable.open = alsa_object_open; self->vtable.close = alsa_object_close; self->vtable.destroy = alsa_object_destroy; self->vtable.write = alsa_object_write; self->vtable.drain = alsa_object_drain; self->vtable.flush = alsa_object_flush; self->vtable.strerror = alsa_object_strerror; return &self->vtable; } #else struct audio_object * create_alsa_object(const char *device, const char *application_name, const char *description) { return NULL; } #endif pcaudiolib-1.2/src/audio.c000066400000000000000000000053241410076607300155330ustar00rootroot00000000000000/* Public API Implementation. * * Copyright (C) 2016 Reece H. Dunn * * This file is part of pcaudiolib. * * pcaudiolib 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. * * pcaudiolib 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 pcaudiolib. If not, see . */ #include "config.h" #include "audio_priv.h" int audio_object_open(struct audio_object *object, enum audio_object_format format, uint32_t rate, uint8_t channels) { if (object) return object->open(object, format, rate, channels); return 0; } void audio_object_close(struct audio_object *object) { if (object) object->close(object); } void audio_object_destroy(struct audio_object *object) { if (object) object->destroy(object); } int audio_object_write(struct audio_object *object, const void *data, size_t bytes) { if (object) return object->write(object, data, bytes); return 0; } int audio_object_drain(struct audio_object *object) { if (object) return object->drain(object); return 0; } int audio_object_flush(struct audio_object *object) { if (object) return object->flush(object); return 0; } const char * audio_object_strerror(struct audio_object *object, int error) { if (object) return object->strerror(object, error); return NULL; } struct audio_object * create_audio_device_object(const char *device, const char *application_name, const char *description) { struct audio_object *object; #if defined(_WIN32) || defined(_WIN64) if ((object = create_xaudio2_object(device, application_name, description)) != NULL) return object; #else #if defined(__APPLE__) if ((object = create_coreaudio_object(device, application_name, description)) != NULL) return object; #else if ((object = create_pulseaudio_object(device, application_name, description)) != NULL) return object; if ((object = create_alsa_object(device, application_name, description)) != NULL) return object; if ((object = create_qsa_object(device, application_name, description)) != NULL) return object; if ((object = create_oss_object(device, application_name, description)) != NULL) return object; #endif #endif return NULL; } pcaudiolib-1.2/src/audio_priv.h000066400000000000000000000063311410076607300165770ustar00rootroot00000000000000/* Internal Audio API. * * Copyright (C) 2016 Reece H. Dunn * * This file is part of pcaudiolib. * * pcaudiolib 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. * * pcaudiolib 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 pcaudiolib. If not, see . */ #ifndef PCAUDIOLIB_AUDIO_PRIV_H #define PCAUDIOLIB_AUDIO_PRIV_H #include #include #ifdef __cplusplus extern "C" { #endif struct audio_object { int (*open)(struct audio_object *object, enum audio_object_format format, uint32_t rate, uint8_t channels); void (*close)(struct audio_object *object); void (*destroy)(struct audio_object *object); int (*write)(struct audio_object *object, const void *data, size_t bytes); int (*drain)(struct audio_object *object); int (*flush)(struct audio_object *object); const char * (*strerror)(struct audio_object *object, int error); }; /* We try to aim for 10ms cancelation latency, which will be perceived as * "snappy" by users */ #define LATENCY 10 #if defined(_WIN32) || defined(_WIN64) #include #define container_of(ptr, type, member) ((type *)( (char *)ptr - offsetof(type,member) )) LPWSTR str2wcs(const char *str); HRESULT CreateWaveFormat(enum audio_object_format format, uint32_t rate, uint8_t channels, WAVEFORMATEX **wfmt); const char * windows_hresult_strerror(struct audio_object *object, int error); struct audio_object * create_xaudio2_object(const char *device, const char *application_name, const char *description); #else #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) #ifdef __APPLE__ struct audio_object * create_coreaudio_object(const char *device, const char *application_name, const char *description); #else struct audio_object * create_pulseaudio_object(const char *device, const char *application_name, const char *description); struct audio_object * create_alsa_object(const char *device, const char *application_name, const char *description); struct audio_object * create_qsa_object(const char *device, const char *application_name, const char *description); struct audio_object * create_oss_object(const char *device, const char *application_name, const char *description); #endif #endif #ifdef __cplusplus } #endif #endif pcaudiolib-1.2/src/coreaudio.c000066400000000000000000000212411410076607300164000ustar00rootroot00000000000000/* Coreaudio Output. * * Copyright (C) 2016 Rui Batista * * This file is part of pcaudiolib. * * pcaudiolib 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. * * pcaudiolib 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 pcaudiolib. If not, see . */ #include "config.h" #include "audio_priv.h" #ifdef HAVE_COREAUDIO_H #include #include #include "TPCircularBuffer/TPCircularBuffer+AudioBufferList.h" #include #include #include #include #define min(a,b) ((a) < (b) ? (a):(b)) #define COREAUDIO_BUFFER_SIZE (1024 * 64) // 4m struct coreaudio_object { struct audio_object vtable; AudioStreamBasicDescription format; AudioUnit outputUnit; TPCircularBuffer circularBuffer; bool initialized; bool running; char *device; char *application_name; char *description; }; #define to_coreaudio_object(object) container_of(object, struct coreaudio_object, vtable) static OSStatus graphRenderProc(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList * ioData) { struct coreaudio_object *self = (struct coreaudio_object *)inRefCon; if(! self->running){ // fill the buffer with sielence, stop was not acnoledged yet memset(ioData->mBuffers[0].mData,0,(self->format).mBytesPerFrame * inNumberFrames); ioData->mBuffers[0].mNumberChannels = 1; ioData->mBuffers[0].mDataByteSize = (self->format).mBytesPerFrame * inNumberFrames; return noErr; } UInt32 available = TPCircularBufferPeek(&(self->circularBuffer), NULL, &(self->format)); if(available == 0) { self->running = FALSE; AudioOutputUnitStop(self->outputUnit); } // copy as much data as we can from the circular buffer TPCircularBufferDequeueBufferListFrames(&(self->circularBuffer), &inNumberFrames, ioData, NULL, &(self->format)); return noErr; } int coreaudio_object_open(struct audio_object *object, enum audio_object_format format, uint32_t rate, uint8_t channels) { struct coreaudio_object *self = to_coreaudio_object(object); OSStatus err = noErr; if (self->initialized) return noErr; memset(&(self->format), 0, sizeof(AudioStreamBasicDescription)); (self->format).mSampleRate = rate; (self->format).mChannelsPerFrame = channels; (self->format).mFramesPerPacket = 1; switch (format) { case AUDIO_OBJECT_FORMAT_S16LE: (self->format).mFormatID = kAudioFormatLinearPCM; (self->format).mBitsPerChannel = 16; (self->format).mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; break; default: return -1; } // guess the remaining of the AudioBasicStreamDescription structure UInt32 procSize = sizeof(AudioStreamBasicDescription); err = AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, 0, NULL, &procSize, &(self->format)); if(err != noErr) { goto cleanup; } // Find default output AudioComponentDescription outputcd = {0,}; outputcd.componentType = kAudioUnitType_Output; outputcd.componentSubType = kAudioUnitSubType_DefaultOutput; outputcd.componentManufacturer = kAudioUnitManufacturer_Apple; // Create a component AudioComponent outputComponent = AudioComponentFindNext(NULL, &outputcd); err = AudioComponentInstanceNew(outputComponent, &(self->outputUnit)); if(err != noErr) { goto cleanup; } // set render callback AURenderCallbackStruct callbackStruct; callbackStruct.inputProcRefCon = self; callbackStruct.inputProc = graphRenderProc; size_t propSize = sizeof(AURenderCallbackStruct); err = AudioUnitSetProperty(self->outputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Output, 0, &callbackStruct, propSize); if(err != noErr) { goto cleanup; } // set output unit input format propSize = sizeof(AudioStreamBasicDescription); err = AudioUnitSetProperty(self->outputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &(self->format), propSize); if(err != noErr) { goto cleanup; } err = AudioUnitInitialize(self->outputUnit); if(err != noErr) { goto cleanup; } // create a circular buffer to produce and consume audio TPCircularBufferInit(&(self->circularBuffer), COREAUDIO_BUFFER_SIZE); self->initialized = TRUE; return noErr; cleanup: if(self->outputUnit) { AudioUnitUninitialize(self->outputUnit); AudioComponentInstanceDispose(self->outputUnit); } return err; } void coreaudio_object_close(struct audio_object *object) { struct coreaudio_object *self = to_coreaudio_object(object); if(self->initialized) { AudioUnitUninitialize(self->outputUnit); AudioComponentInstanceDispose(self->outputUnit); TPCircularBufferCleanup(&(self->circularBuffer)); self->initialized = FALSE; } } void coreaudio_object_destroy(struct audio_object *object) { struct coreaudio_object *self = to_coreaudio_object(object); } int coreaudio_object_drain(struct audio_object *object) { struct coreaudio_object *self = to_coreaudio_object(object); if (!self->initialized) return noErr; while(self->running) usleep(10000); return noErr; } int coreaudio_object_flush(struct audio_object *object) { struct coreaudio_object *self = to_coreaudio_object(object); if (!self->initialized) return noErr; OSStatus err = AudioOutputUnitStop(self->outputUnit); TPCircularBufferClear(&(self->circularBuffer)); self->running = FALSE; return err; } int coreaudio_object_write(struct audio_object *object, const void *data, size_t bytes) { struct coreaudio_object *self = to_coreaudio_object(object); if (!self->initialized) return noErr; bool runningAtStart = self->running; if(!runningAtStart) { TPCircularBufferClear(&(self->circularBuffer)); } char *dataPtr = (char*)data; // copy data to our circular buffer // Poll while we don't have space in the buffer. AudioBufferList *bufferList; UInt32 available; while(bytes > 0) { while((!runningAtStart || self->running) && (available = TPCircularBufferGetAvailableSpace(&(self->circularBuffer), &(self->format))) == 0) usleep(10000); // check we didn't stop if(runningAtStart && (!self->running)) return noErr; bufferList = TPCircularBufferPrepareEmptyAudioBufferListWithAudioFormat(&(self->circularBuffer), &(self->format), available, NULL); // we are writing mono/interleaved data so we have one buffer UInt32 bytesToWrite = min(bytes, bufferList->mBuffers[0].mDataByteSize); bufferList->mBuffers[0].mNumberChannels = (self->format).mChannelsPerFrame; bufferList->mBuffers[0].mDataByteSize = bytesToWrite; memcpy(bufferList->mBuffers[0].mData, dataPtr, bytesToWrite); TPCircularBufferProduceAudioBufferList(&(self->circularBuffer), NULL); dataPtr += bytesToWrite; bytes -= bytesToWrite; if(! runningAtStart) { OSStatus err = AudioOutputUnitStart(self->outputUnit); if(err == noErr) { self->running = TRUE; runningAtStart = TRUE; } else { return err; } } } return noErr; } const char * coreaudio_object_strerror(struct audio_object *object, int error) { return GetMacOSStatusCommentString(error); } static bool coreaudio_is_available(const char *device, const char *application_name, const char *description) { return true; } struct audio_object * create_coreaudio_object(const char *device, const char *application_name, const char *description) { if (!coreaudio_is_available(device, application_name, description)) return NULL; struct coreaudio_object *self = malloc(sizeof(struct coreaudio_object)); if (!self) return NULL; self->vtable.open = coreaudio_object_open; self->vtable.close = coreaudio_object_close; self->vtable.destroy = coreaudio_object_destroy; self->vtable.write = coreaudio_object_write; self->vtable.drain = coreaudio_object_drain; self->vtable.flush = coreaudio_object_flush; self->vtable.strerror = coreaudio_object_strerror; return &self->vtable; } #else struct audio_object * create_coreaudio_object(const char *device, const char *application_name, const char *description) { return NULL; } #endif pcaudiolib-1.2/src/include/000077500000000000000000000000001410076607300157055ustar00rootroot00000000000000pcaudiolib-1.2/src/include/pcaudiolib/000077500000000000000000000000001410076607300200205ustar00rootroot00000000000000pcaudiolib-1.2/src/include/pcaudiolib/audio.h000066400000000000000000000054471410076607300213040ustar00rootroot00000000000000/* Audio API. * * Copyright (C) 2016 Reece H. Dunn * * This file is part of pcaudiolib. * * pcaudiolib 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. * * pcaudiolib 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 pcaudiolib. If not, see . */ #ifndef PCAUDIOLIB_AUDIO_H #define PCAUDIOLIB_AUDIO_H #include #include #ifdef __cplusplus extern "C" { #endif enum audio_object_format { AUDIO_OBJECT_FORMAT_S8, AUDIO_OBJECT_FORMAT_U8, AUDIO_OBJECT_FORMAT_S16LE, AUDIO_OBJECT_FORMAT_S16BE, AUDIO_OBJECT_FORMAT_U16LE, AUDIO_OBJECT_FORMAT_U16BE, AUDIO_OBJECT_FORMAT_S18LE, AUDIO_OBJECT_FORMAT_S18BE, AUDIO_OBJECT_FORMAT_U18LE, AUDIO_OBJECT_FORMAT_U18BE, AUDIO_OBJECT_FORMAT_S20LE, AUDIO_OBJECT_FORMAT_S20BE, AUDIO_OBJECT_FORMAT_U20LE, AUDIO_OBJECT_FORMAT_U20BE, AUDIO_OBJECT_FORMAT_S24LE, AUDIO_OBJECT_FORMAT_S24BE, AUDIO_OBJECT_FORMAT_U24LE, AUDIO_OBJECT_FORMAT_U24BE, AUDIO_OBJECT_FORMAT_S24_32LE, AUDIO_OBJECT_FORMAT_S24_32BE, AUDIO_OBJECT_FORMAT_U24_32LE, AUDIO_OBJECT_FORMAT_U24_32BE, AUDIO_OBJECT_FORMAT_S32LE, AUDIO_OBJECT_FORMAT_S32BE, AUDIO_OBJECT_FORMAT_U32LE, AUDIO_OBJECT_FORMAT_U32BE, AUDIO_OBJECT_FORMAT_FLOAT32LE, AUDIO_OBJECT_FORMAT_FLOAT32BE, AUDIO_OBJECT_FORMAT_FLOAT64LE, AUDIO_OBJECT_FORMAT_FLOAT64BE, AUDIO_OBJECT_FORMAT_IEC958LE, AUDIO_OBJECT_FORMAT_IEC958BE, AUDIO_OBJECT_FORMAT_ALAW, AUDIO_OBJECT_FORMAT_ULAW, AUDIO_OBJECT_FORMAT_ADPCM, AUDIO_OBJECT_FORMAT_MPEG, AUDIO_OBJECT_FORMAT_GSM, AUDIO_OBJECT_FORMAT_AC3, }; struct audio_object; int audio_object_open(struct audio_object *object, enum audio_object_format format, uint32_t rate, uint8_t channels); void audio_object_close(struct audio_object *object); void audio_object_destroy(struct audio_object *object); int audio_object_write(struct audio_object *object, const void *data, size_t bytes); int audio_object_drain(struct audio_object *object); int audio_object_flush(struct audio_object *object); const char * audio_object_strerror(struct audio_object *object, int error); struct audio_object * create_audio_device_object(const char *device, const char *application_name, const char *description); #ifdef __cplusplus } #endif #endif pcaudiolib-1.2/src/oss.c000066400000000000000000000113261410076607300152350ustar00rootroot00000000000000/* OSS Output. * * Copyright (C) 2016 Reece H. Dunn * * This file is part of pcaudiolib. * * pcaudiolib 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. * * pcaudiolib 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 pcaudiolib. If not, see . */ #include "config.h" #include "audio_priv.h" #if defined(HAVE_SYS_SOUNDCARD_H) #include #define DEFAULT_OSS_DEVICE "/dev/dsp" #elif defined(HAVE_LINUX_SOUNDCARD_H) #include #define DEFAULT_OSS_DEVICE "/dev/dsp" #elif defined(HAVE_SOUNDCARD_H) #include #define DEFAULT_OSS_DEVICE "/dev/dsp" #endif #ifdef DEFAULT_OSS_DEVICE #include #include #include #include #include #include struct oss_object { struct audio_object vtable; int fd; char *device; }; #define to_oss_object(object) container_of(object, struct oss_object, vtable) int oss_object_open(struct audio_object *object, enum audio_object_format format, uint32_t rate, uint8_t channels) { struct oss_object *self = to_oss_object(object); if (self->fd != -1) return EEXIST; int oss_format; switch (format) { case AUDIO_OBJECT_FORMAT_ALAW: oss_format = AFMT_A_LAW; break; case AUDIO_OBJECT_FORMAT_ULAW: oss_format = AFMT_MU_LAW; break; case AUDIO_OBJECT_FORMAT_S8: oss_format = AFMT_S8; break; case AUDIO_OBJECT_FORMAT_U8: oss_format = AFMT_U8; break; case AUDIO_OBJECT_FORMAT_S16LE: oss_format = AFMT_S16_LE; break; case AUDIO_OBJECT_FORMAT_S16BE: oss_format = AFMT_S16_BE; break; case AUDIO_OBJECT_FORMAT_U16LE: oss_format = AFMT_U16_LE; break; case AUDIO_OBJECT_FORMAT_U16BE: oss_format = AFMT_U16_BE; break; case AUDIO_OBJECT_FORMAT_ADPCM: oss_format = AFMT_IMA_ADPCM; break; case AUDIO_OBJECT_FORMAT_MPEG: oss_format = AFMT_MPEG; break; #if defined AFMT_AC3 case AUDIO_OBJECT_FORMAT_AC3: oss_format = AFMT_AC3; break; #endif default: return EINVAL; } int data; if ((self->fd = open(self->device ? self->device : DEFAULT_OSS_DEVICE, O_RDWR, 0)) == -1) return errno; if (ioctl(self->fd, SNDCTL_DSP_SETFMT, &oss_format) == -1) goto error; data = rate; if (ioctl(self->fd, SNDCTL_DSP_SPEED, &data) == -1) goto error; data = channels; if (ioctl(self->fd, SNDCTL_DSP_CHANNELS, &data) == -1) goto error; return 0; error: data = errno; close(self->fd); self->fd = -1; return data; } void oss_object_close(struct audio_object *object) { struct oss_object *self = to_oss_object(object); if (self->fd == -1) { close(self->fd); self->fd = -1; } } void oss_object_destroy(struct audio_object *object) { struct oss_object *self = to_oss_object(object); free(self->device); free(self); } int oss_object_drain(struct audio_object *object) { struct oss_object *self = to_oss_object(object); if (ioctl(self->fd, SNDCTL_DSP_SYNC, NULL) == -1) return errno; return 0; } int oss_object_flush(struct audio_object *object) { struct oss_object *self = to_oss_object(object); if (ioctl(self->fd, SNDCTL_DSP_RESET, NULL) == -1) return errno; return 0; } int oss_object_write(struct audio_object *object, const void *data, size_t bytes) { struct oss_object *self = to_oss_object(object); if (write(self->fd, data, bytes) == -1) return errno; return 0; } const char * oss_object_strerror(struct audio_object *object, int error) { return strerror(error); } struct audio_object * create_oss_object(const char *device, const char *application_name, const char *description) { struct oss_object *self = malloc(sizeof(struct oss_object)); if (!self) return NULL; self->fd = -1; self->device = device ? strdup(device) : NULL; self->vtable.open = oss_object_open; self->vtable.close = oss_object_close; self->vtable.destroy = oss_object_destroy; self->vtable.write = oss_object_write; self->vtable.drain = oss_object_drain; self->vtable.flush = oss_object_flush; self->vtable.strerror = oss_object_strerror; return &self->vtable; } #else struct audio_object * create_oss_object(const char *device, const char *application_name, const char *description) { return NULL; } #endif pcaudiolib-1.2/src/pulseaudio.c000066400000000000000000000144461410076607300166110ustar00rootroot00000000000000/* PulseAudio Output. * * Copyright (C) 2016 Reece H. Dunn * * This file is part of pcaudiolib. * * pcaudiolib 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. * * pcaudiolib 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 pcaudiolib. If not, see . */ #include "config.h" #include "audio_priv.h" #ifdef HAVE_PULSE_SIMPLE_H #include #include #include #include struct pulseaudio_object { struct audio_object vtable; pa_sample_spec ss; pa_simple *s; char *device; char *application_name; char *description; }; #define to_pulseaudio_object(object) container_of(object, struct pulseaudio_object, vtable) int pulseaudio_object_open(struct audio_object *object, enum audio_object_format format, uint32_t rate, uint8_t channels) { struct pulseaudio_object *self = to_pulseaudio_object(object); if (self->s) return PA_ERR_EXIST; self->ss.rate = rate; self->ss.channels = channels; switch (format) { case AUDIO_OBJECT_FORMAT_ALAW: self->ss.format = PA_SAMPLE_ALAW; break; case AUDIO_OBJECT_FORMAT_ULAW: self->ss.format = PA_SAMPLE_ULAW; break; case AUDIO_OBJECT_FORMAT_U8: self->ss.format = PA_SAMPLE_U8; break; case AUDIO_OBJECT_FORMAT_S16LE: self->ss.format = PA_SAMPLE_S16LE; break; case AUDIO_OBJECT_FORMAT_S16BE: self->ss.format = PA_SAMPLE_S16BE; break; #ifdef PA_SAMPLE_S24LE case AUDIO_OBJECT_FORMAT_S24LE: self->ss.format = PA_SAMPLE_S24LE; break; case AUDIO_OBJECT_FORMAT_S24BE: self->ss.format = PA_SAMPLE_S24BE; break; case AUDIO_OBJECT_FORMAT_S24_32LE: self->ss.format = PA_SAMPLE_S24_32LE; break; case AUDIO_OBJECT_FORMAT_S24_32BE: self->ss.format = PA_SAMPLE_S24_32BE; break; #endif case AUDIO_OBJECT_FORMAT_S32LE: self->ss.format = PA_SAMPLE_S32LE; break; case AUDIO_OBJECT_FORMAT_S32BE: self->ss.format = PA_SAMPLE_S32BE; break; case AUDIO_OBJECT_FORMAT_FLOAT32LE: self->ss.format = PA_SAMPLE_FLOAT32LE; break; case AUDIO_OBJECT_FORMAT_FLOAT32BE: self->ss.format = PA_SAMPLE_FLOAT32BE; break; default: return PA_ERR_INVALID; // Invalid argument. } int error = 0; pa_buffer_attr battr; battr.fragsize = (uint32_t) -1; battr.maxlength = (uint32_t) -1; battr.minreq = (uint32_t) -1; battr.prebuf = (uint32_t) -1; battr.tlength = pa_bytes_per_second(&self->ss) * LATENCY / 1000; self->s = pa_simple_new(NULL, self->application_name, PA_STREAM_PLAYBACK, self->device, self->description, &self->ss, NULL, &battr, &error); return error; } void pulseaudio_object_close(struct audio_object *object) { struct pulseaudio_object *self = to_pulseaudio_object(object); if (self->s) { pa_simple_free(self->s); self->s = NULL; } } void pulseaudio_object_destroy(struct audio_object *object) { struct pulseaudio_object *self = to_pulseaudio_object(object); free(self->device); free(self->application_name); free(self->description); free(self); } int pulseaudio_object_drain(struct audio_object *object) { struct pulseaudio_object *self = to_pulseaudio_object(object); if (!self->s) return 0; int error = 0; pa_simple_drain(self->s, &error); return error; } int pulseaudio_object_flush(struct audio_object *object) { struct pulseaudio_object *self = to_pulseaudio_object(object); if (!self->s) return 0; int error = 0; pa_simple_flush(self->s, &error); return error; } int pulseaudio_object_write(struct audio_object *object, const void *data, size_t bytes) { struct pulseaudio_object *self = to_pulseaudio_object(object); if (!self->s) return 0; int error = 0; pa_simple_write(self->s, data, bytes, &error); return error; } const char * pulseaudio_object_strerror(struct audio_object *object, int error) { return pa_strerror(error); } static bool pulseaudio_is_available(const char *device, const char *application_name, const char *description) { pa_sample_spec ss; ss.format = PA_SAMPLE_S16LE; ss.rate = 44100; ss.channels = 1; pa_simple *s = pa_simple_new(NULL, application_name, PA_STREAM_PLAYBACK, device, description, &ss, NULL, NULL, NULL); if (!s) return false; pa_simple_free(s); return true; } struct audio_object * create_pulseaudio_object(const char *device, const char *application_name, const char *description) { if (!pulseaudio_is_available(device, application_name, description)) return NULL; struct pulseaudio_object *self = malloc(sizeof(struct pulseaudio_object)); if (!self) return NULL; self->s = NULL; self->device = device ? strdup(device) : NULL; self->application_name = application_name ? strdup(application_name) : NULL; self->description = description ? strdup(description) : NULL; self->vtable.open = pulseaudio_object_open; self->vtable.close = pulseaudio_object_close; self->vtable.destroy = pulseaudio_object_destroy; self->vtable.write = pulseaudio_object_write; self->vtable.drain = pulseaudio_object_drain; self->vtable.flush = pulseaudio_object_flush; self->vtable.strerror = pulseaudio_object_strerror; return &self->vtable; } #else struct audio_object * create_pulseaudio_object(const char *device, const char *application_name, const char *description) { return NULL; } #endif pcaudiolib-1.2/src/qsa.c000066400000000000000000000127421410076607300152200ustar00rootroot00000000000000/* QSA Output. * * Copyright (C) 2016 Reece H. Dunn * Copyright (C) 2016 Kaj-Michael Lang * * This file is part of pcaudiolib. * * pcaudiolib 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. * * pcaudiolib 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 pcaudiolib. If not, see . */ #include "config.h" #include "audio_priv.h" #if defined(HAVE_SYS_ASOUNDLIB_H) && defined(HAVE_SYS_ASOUND_H) #include #include #include #include struct qsa_object { struct audio_object vtable; snd_pcm_t *handle; uint8_t sample_size; char *device; }; #define to_qsa_object(object) container_of(object, struct qsa_object, vtable) int qsa_object_open(struct audio_object *object, enum audio_object_format format, uint32_t rate, uint8_t channels) { struct qsa_object *self = to_qsa_object(object); if (self->handle) return -EEXIST; int pcm_format; #define FORMAT(srcfmt, dstfmt, size) case srcfmt: pcm_format = dstfmt; self->sample_size = size; break; switch (format) { FORMAT(AUDIO_OBJECT_FORMAT_U8, SND_PCM_SFMT_U8, 1) FORMAT(AUDIO_OBJECT_FORMAT_S8, SND_PCM_SFMT_S8, 1) FORMAT(AUDIO_OBJECT_FORMAT_S16LE, SND_PCM_SFMT_S16_LE, 2) default: return -EINVAL; } #undef FORMAT snd_pcm_info_t pi; snd_pcm_channel_info_t pci; snd_pcm_channel_params_t pp; snd_pcm_channel_setup_t setup; int err = 0; if (self->device) { if ((err = snd_pcm_open_name(&self->handle, self->device, SND_PCM_OPEN_PLAYBACK)) < 0) goto error; } else { if ((err = snd_pcm_open_preferred(&self->handle, NULL, NULL, SND_PCM_OPEN_PLAYBACK)) < 0) goto error; } memset (&pi, 0, sizeof (pi)); if ((err = snd_pcm_info (self->handle, &pi)) < 0) goto error; memset (&pci, 0, sizeof (pci)); pci.channel = SND_PCM_CHANNEL_PLAYBACK; if ((err = snd_pcm_plugin_info (self->handle, &pci)) < 0) goto error; memset (&pp, 0, sizeof (pp)); pp.mode = SND_PCM_MODE_BLOCK; pp.channel = SND_PCM_CHANNEL_PLAYBACK; pp.start_mode = SND_PCM_START_FULL; pp.stop_mode = SND_PCM_STOP_STOP; pp.buf.block.frag_size = pci.max_fragment_size; pp.buf.block.frags_max = 4; // XXX: What should this be? pp.buf.block.frags_min = 1; pp.format.interleave = 1; pp.format.rate = rate; pp.format.voices = channels; pp.format.format = pcm_format; if ((err = snd_pcm_plugin_params (self->handle, &pp)) < 0) goto error; if ((err = snd_pcm_plugin_prepare (self->handle, SND_PCM_CHANNEL_PLAYBACK)) < 0) goto error; return 0; error: if (self->handle) { snd_pcm_close(self->handle); self->handle = NULL; } return err; } void qsa_object_close(struct audio_object *object) { struct qsa_object *self = to_qsa_object(object); if (self->handle) { snd_pcm_close(self->handle); self->handle = NULL; } } void qsa_object_destroy(struct audio_object *object) { struct qsa_object *self = to_qsa_object(object); free(self->device); free(self); } int qsa_object_drain(struct audio_object *object) { struct qsa_object *self = to_qsa_object(object); return snd_pcm_plugin_playback_drain(self->handle); } int qsa_object_flush(struct audio_object *object) { struct qsa_object *self = to_qsa_object(object); return snd_pcm_plugin_flush(self->handle, SND_PCM_CHANNEL_PLAYBACK); } int qsa_object_write(struct audio_object *object, const void *data, size_t bytes) { struct qsa_object *self = to_qsa_object(object); snd_pcm_channel_status_t status; size_t written = snd_pcm_plugin_write(self->handle, data, bytes); if (written < bytes) { int err; memset (&status, 0, sizeof (status)); status.channel = SND_PCM_CHANNEL_PLAYBACK; err=snd_pcm_plugin_status (self->handle, &status); if (err < 0) { return err; } if (status.status == SND_PCM_STATUS_READY || status.status == SND_PCM_STATUS_UNDERRUN) { err = snd_pcm_plugin_prepare(self->handle, SND_PCM_CHANNEL_PLAYBACK); // Try again if we can if (err==0 && written==0) return snd_pcm_plugin_write(self->handle, data, bytes); } return err; } return 0; } const char * qsa_object_strerror(struct audio_object *object, int error) { return snd_strerror(error); } struct audio_object * create_qsa_object(const char *device, const char *application_name, const char *description) { struct qsa_object *self = malloc(sizeof(struct qsa_object)); if (!self) return NULL; self->handle = NULL; self->sample_size = 0; self->device = device ? strdup(device) : NULL; self->vtable.open = qsa_object_open; self->vtable.close = qsa_object_close; self->vtable.destroy = qsa_object_destroy; self->vtable.write = qsa_object_write; self->vtable.drain = qsa_object_drain; self->vtable.flush = qsa_object_flush; self->vtable.strerror = qsa_object_strerror; return &self->vtable; } #else struct audio_object * create_qsa_object(const char *device, const char *application_name, const char *description) { return NULL; } #endif pcaudiolib-1.2/src/windows.c000066400000000000000000000061621410076607300161250ustar00rootroot00000000000000/* Windows Helpers for Writing Windows Audio Objects. * * Copyright (C) 2016 Reece H. Dunn * * This file is part of pcaudiolib. * * pcaudiolib 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. * * pcaudiolib 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 pcaudiolib. If not, see . */ #include "config.h" #include "audio_priv.h" #include LPWSTR str2wcs(const char *str) { size_t len = strlen(str); LPWSTR ret = calloc(len + 1, sizeof(wchar_t)); if (!ret) return NULL; mbstowcs(ret, str, len + 1); return ret; } static HRESULT CreateWaveFormatEx(WORD format, uint32_t bits_per_sample, uint32_t rate, uint8_t channels, WAVEFORMATEX **wfmt) { (*wfmt) = CoTaskMemAlloc(sizeof(WAVEFORMATEX)); if (!(*wfmt)) return E_OUTOFMEMORY; (*wfmt)->wFormatTag = format; (*wfmt)->nChannels = channels; (*wfmt)->nBlockAlign = (channels * bits_per_sample) / 8; (*wfmt)->nSamplesPerSec = rate; (*wfmt)->wBitsPerSample = bits_per_sample; (*wfmt)->nAvgBytesPerSec = rate * (*wfmt)->nBlockAlign; (*wfmt)->cbSize = 0; return S_OK; } HRESULT CreateWaveFormat(enum audio_object_format format, uint32_t rate, uint8_t channels, WAVEFORMATEX **wfmt) { if (!wfmt) return E_INVALIDARG; switch (format) { case AUDIO_OBJECT_FORMAT_ALAW: return CreateWaveFormatEx(WAVE_FORMAT_ALAW, 8, rate, channels, wfmt); case AUDIO_OBJECT_FORMAT_ULAW: return CreateWaveFormatEx(WAVE_FORMAT_MULAW, 8, rate, channels, wfmt); case AUDIO_OBJECT_FORMAT_S8: return CreateWaveFormatEx(WAVE_FORMAT_PCM, 8, rate, channels, wfmt); case AUDIO_OBJECT_FORMAT_S16LE: return CreateWaveFormatEx(WAVE_FORMAT_PCM, 16, rate, channels, wfmt); case AUDIO_OBJECT_FORMAT_S32LE: return CreateWaveFormatEx(WAVE_FORMAT_PCM, 32, rate, channels, wfmt); case AUDIO_OBJECT_FORMAT_FLOAT32LE: return CreateWaveFormatEx(WAVE_FORMAT_IEEE_FLOAT, 32, rate, channels, wfmt); case AUDIO_OBJECT_FORMAT_FLOAT64LE: return CreateWaveFormatEx(WAVE_FORMAT_IEEE_FLOAT, 64, rate, channels, wfmt); default: return E_INVALIDARG; } } const char * windows_hresult_strerror(struct audio_object *object, int error) { char *msg = NULL; DWORD result = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &msg, 256, NULL); if (!result) return NULL; size_t len = strlen(msg); while (len > 1 && msg[len - 1] == '\n' || msg[len - 1] == '\r') msg[--len] = 0; char *ret = strdup(msg); LocalFree(msg); return ret; } pcaudiolib-1.2/src/xaudio2.cpp000066400000000000000000000105521410076607300163440ustar00rootroot00000000000000/* Windows xAudio2 API Output. * * Copyright (C) 2016 Reece H. Dunn * * This file is part of pcaudiolib. * * pcaudiolib 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. * * pcaudiolib 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 pcaudiolib. If not, see . */ #include "config.h" #include "audio_priv.h" // NOTE: XAudio2.h fails to build with a C compiler #include #pragma comment(lib, "xaudio2.lib") struct xaudio2_object { struct audio_object vtable; IXAudio2 *audio; IXAudio2MasteringVoice *mastering; IXAudio2SourceVoice *source; WAVEFORMATEX *format; LPWSTR devicename; }; void xaudio2_object_close(struct audio_object *object); #define to_xaudio2_object(object) container_of(object, struct xaudio2_object, vtable) int xaudio2_object_open(struct audio_object *object, enum audio_object_format format, uint32_t rate, uint8_t channels) { struct xaudio2_object *self = to_xaudio2_object(object); if (self->mastering != NULL) return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED); HRESULT hr; hr = self->audio->CreateMasteringVoice(&self->mastering); if (FAILED(hr)) goto error; hr = CreateWaveFormat(format, rate, channels, &self->format); if (FAILED(hr)) goto error; hr = self->audio->CreateSourceVoice(&self->source, self->format); if (FAILED(hr)) goto error; return S_OK; error: xaudio2_object_close(object); return hr; } void xaudio2_object_close(struct audio_object *object) { struct xaudio2_object *self = to_xaudio2_object(object); if (self->source != NULL) { self->source->DestroyVoice(); self->source = NULL; } if (self->format != NULL) { CoTaskMemFree(self->format); self->format = NULL; } if (self->mastering != NULL) { self->mastering->DestroyVoice(); self->mastering = NULL; } } void xaudio2_object_destroy(struct audio_object *object) { struct xaudio2_object *self = to_xaudio2_object(object); self->audio->Release(); free(self->devicename); free(self); CoUninitialize(); } int xaudio2_object_drain(struct audio_object *object) { struct xaudio2_object *self = to_xaudio2_object(object); return S_OK; } int xaudio2_object_flush(struct audio_object *object) { struct xaudio2_object *self = to_xaudio2_object(object); return S_OK; } int xaudio2_object_write(struct audio_object *object, const void *data, size_t bytes) { struct xaudio2_object *self = to_xaudio2_object(object); XAUDIO2_BUFFER buffer = {0}; buffer.AudioBytes = bytes; buffer.pAudioData = (const BYTE *)data; HRESULT hr = S_OK; if (SUCCEEDED(hr)) hr = self->source->SubmitSourceBuffer(&buffer); if (SUCCEEDED(hr)) hr = self->source->Start(0); if (SUCCEEDED(hr)) while (true) { Sleep(10); XAUDIO2_VOICE_STATE state = { 0 }; self->source->GetState(&state); if (state.pCurrentBufferContext == NULL && state.BuffersQueued == 0) return hr; } return hr; } struct audio_object * create_xaudio2_object(const char *device, const char *application_name, const char *description) { CoInitialize(NULL); IXAudio2 *audio = NULL; HRESULT hr = XAudio2Create(&audio, 0, XAUDIO2_DEFAULT_PROCESSOR); if (FAILED(hr) || audio == NULL) { if (audio != NULL) audio->Release(); CoUninitialize(); return NULL; } struct xaudio2_object *self = (struct xaudio2_object *)malloc(sizeof(struct xaudio2_object)); if (!self) return NULL; self->audio = audio; self->mastering = NULL; self->source = NULL; self->format = NULL; self->devicename = device ? str2wcs(device) : NULL; self->vtable.open = xaudio2_object_open; self->vtable.close = xaudio2_object_close; self->vtable.destroy = xaudio2_object_destroy; self->vtable.write = xaudio2_object_write; self->vtable.drain = xaudio2_object_drain; self->vtable.flush = xaudio2_object_flush; self->vtable.strerror = windows_hresult_strerror; return &self->vtable; }