Initial community commit

This commit is contained in:
Jef 2024-09-24 14:54:57 +02:00
parent 537bcbc862
commit fc06254474
16440 changed files with 4239995 additions and 2 deletions

View file

@ -0,0 +1,81 @@
Portable header file to contain:
>>>>>
/*
* PortAudio Portable Real-Time Audio Library
* PortAudio API Header File
* Latest version available at: http://www.portaudio.com
*
* Copyright (c) 1999-2006 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
<<<<<
Implementation files to contain:
>>>>>
/*
* PortAudio Portable Real-Time Audio Library
* Latest version at: http://www.portaudio.com
* <platform> Implementation
* Copyright (c) 1999-2000 <author(s)>
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
<<<<<

View file

@ -0,0 +1,21 @@
* Portaudio v19.7.0 (2021-04-06)
* `build/msvc/portaudio.def` has been modified. Modifications are marked with
`;OpenMPT`.
* `src/hostapi/dsound/pa_win_ds.c` unconditionally defined `_WIN32_WINNT`.
Only define it if it has not been defined already. Modifications have been
marked with `// OpenMPT`.
* A small modification to portaudio code has been made in
`src/hostapi/wdmks/pa_win_wdmks.c` to facilitate linking against
`strmiids.lib`. Modifications have been marked with `// OpenMPT`.
* `src/os/win/pa_x86_plain_converters.c` has been modified to exclude inline
asm for non-x86 platforms. Modifications have been marked with `// OpenMPT`.
* A couple of unnecessary folders have been omitted in SVN:
bindings, cmake_support, doc, examples, pablio, test, testcvs
* For building, premake is used to generate Visual Studio project files.
See ../build/premake/ for details.
> NOTE: Various versions of the Windows SDK (such as the one provided with
> the VS2008 x64 compiler) do not provide ksguid.lib. To simplify the build
> configuration, PA_WDMKS_NO_KSGUID_LIB is defined in the premake projects
> to always use PortAudio's workaround, regardless of the compiler version
> used.
* Unnecssary files have been removed.

View file

@ -0,0 +1,62 @@
# PortAudio - portable audio I/O library
PortAudio is a portable audio I/O library designed for cross-platform
support of audio. It uses either a callback mechanism to request audio
processing, or blocking read/write calls to buffer data between the
native audio subsystem and the client. Audio can be processed in various
formats, including 32 bit floating point, and will be converted to the
native format internally.
## Documentation:
* Documentation is available at http://www.portaudio.com/docs/
* Or at `/doc/html/index.html` after running Doxygen.
* Also see `src/common/portaudio.h` for the API spec.
* And see the `examples/` and `test/` directories for many examples of usage. (We suggest `examples/paex_saw.c` for an example.)
For information on compiling programs with PortAudio, please see the
tutorial at:
http://portaudio.com/docs/v19-doxydocs/tutorial_start.html
We have an active mailing list for user and developer discussions.
Please feel free to join. See http://www.portaudio.com for details.
## Important Files and Folders:
include/portaudio.h = header file for PortAudio API. Specifies API.
src/common/ = platform independent code, host independent
code for all implementations.
src/os = os specific (but host api neutral) code
src/hostapi = implementations for different host apis
### Host API Implementations:
src/hostapi/alsa = Advanced Linux Sound Architecture (ALSA)
src/hostapi/asihpi = AudioScience HPI
src/hostapi/asio = ASIO for Windows and Macintosh
src/hostapi/coreaudio = Macintosh Core Audio for OS X
src/hostapi/dsound = Windows Direct Sound
src/hostapi/jack = JACK Audio Connection Kit
src/hostapi/oss = Unix Open Sound System (OSS)
src/hostapi/wasapi = Windows Vista WASAPI
src/hostapi/wdmks = Windows WDM Kernel Streaming
src/hostapi/wmme = Windows MultiMedia Extensions (MME)
### Test Programs:
test/pa_fuzz.c = guitar fuzz box
test/pa_devs.c = print a list of available devices
test/pa_minlat.c = determine minimum latency for your machine
test/paqa_devs.c = self test that opens all devices
test/paqa_errs.c = test error detection and reporting
test/patest_clip.c = hear a sine wave clipped and unclipped
test/patest_dither.c = hear effects of dithering (extremely subtle)
test/patest_pink.c = fun with pink noise
test/patest_record.c = record and playback some audio
test/patest_maxsines.c = how many sine waves can we play? Tests Pa_GetCPULoad().
test/patest_sine.c = output a sine wave in a simple PA app
test/patest_sync.c = test synchronization of audio and video
test/patest_wire.c = pass input to output, wire simulator

View file

@ -0,0 +1,31 @@
PortAudio Portable Real-Time Audio Library
Copyright (c) 1999-2006 Ross Bencina and Phil Burk
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.
The text above constitutes the entire PortAudio license; however,
the PortAudio community also makes the following non-binding requests:
Any person wishing to distribute modifications to the Software is
requested to send the modifications to the original developer so that
they can be incorporated into the canonical version. It is also
requested that these non-binding requests be included along with the
license above.

View file

@ -0,0 +1,178 @@
Note: Because PortAudioCpp is now in the main PortAudio SVN repository, having these per-release changelogs probably doesn't make much sense anymore. Perhaps it's better to just note mayor changes by date from now on.
PortAudioCpp v19 revision 16 06/05/22:
mblaauw:
- Added up-to-date MSVC 6.0 projects created by David Moore. Besides MSVC 6.0 users, MSVC 7.0 users may use these projects and automatically convert them to MSVC 7.0 projects.
- Changed the code and projects (MSVC 7.1 only) to be up-to-date with PortAudio's new directory structure.
- Added equivalents of the PaAsio_GetInputChannelName() and PaAsio_GetOutputChannelName() functions to the AsioDeviceAdapter wrapper-class (missing functions pointed out by David Moore).
- Added code to PortAudio's main SVN repository.
PortAudioCpp v19 revision 15 (unknown release date):
mblaauw:
- Changed some exception handling code in HostApi's constructor.
- Added accessors to PortAudio PaStream from PortAudioCpp Stream (their absence being pointed out
by Tom Jordan).
- Fixed a bug/typo in MemFunToCallbackInterfaceAdapter::init() thanks to Fredrik Viklund.
- Fixed issue with concrete Stream classes possibly throwing an exception and fixed documentation w.r.t. this.
- Moved files to portaudio/binding/cpp/. Made new msvc 7.1 projects to reflect the change and removed msvc 6.0
and 7.0 projects (because I can no longer maintain them myself). Gnu projects will probably need updating.
PortAudioCpp v19 revision 14 03/10/24:
mblaauw:
- Fixed some error handling bugs in Stream and System (pointed out by Tom Jordan).
- Updated documentation a little (main page).
- Fixed order of members so initializer list was in the right order in
StreamParameters (pointed out by Ludwig Schwardt).
- Added new lines at EOF's (as indicated by Ludwig Schwardt).
PortAudioCpp v19 revision 13 03/10/19:
lschwardt:
- Added build files for GNU/Linux.
- Fixed bug in Exception where the inherited what() member function (and destructor) had looser
exception specification (namely no exception specification, i.e. could throw anything) than
the std::exception base class's what() member function (which had throw(), i.e. no-throw guarantee).
- Changed the iterators so that they have a set of public typedefs instead of deriving the C++ standard
library std::iterator<> struct. G++ 2.95 doesn't support std::exception<> and composition-by-aggregation
is preferred over composition-by-inheritance in this case.
- Changed some minor things to avoid G++ warning messages.
mblaauw:
- Renamed this file (/WHATSNEW.txt) to /CHANGELOG.
- Renamed /PA_ISSUES.txt to /PA_ISSUES.
- Added /INSTALL file with some build info for GNU/Linux and VC6.
- Added MSVC 6.0 projects for building PortAudioCpp as a statically or dynamically linkable library.
- Moved build files to /build/(gnu/ or vc6/).
- Moved Doxygen configuration files to /doc/ and output to /doc/api_reference/.
- Added a /doc/README with some info how to generate Doxygen documentation.
PortAudioCpp v19 revision 12 03/09/02:
mblaauw:
- Updated code to reflect changes on V19-devel CVS branch.
- Fixed some typos in the documentation.
PortAudioCpp v19 revision 11 03/07/31:
mblaauw:
- Renamed SingleDirecionStreamParameters to DirectionSpecificStreamParameters.
- Implemented BlockingStream.
- Updated code to reflect recent changes to PortAudio V19-devel.
- Fixed a potential memory leak when an exception was thrown in the HostApi
constructor.
- Renamed ``Latency'' to ``BufferSize'' in AsioDeviceAdapter.
- Updated class documentation.
PortAudioCpp v19 revision 10 03/07/18:
mblaauw:
- SingleDirectionStreamParameters now has a (static) null() method.
- StreamParameters uses references for the direction-specific stream parameters
instead of pointers (use null() method (above) instead of NULL).
- StreamParameters and SingleDirectionStreamParameters must now be fully specified
and now default values are used (because this was not very useful in general and
only made things more complex).
- Updated documentation.
PortAudioCpp v19 revision 09 03/06/25:
mblaauw:
- Changed some things in SingleDirectionStreamParameters to ease it's usage.
- Placed all SingleDirectionStreamParameters stuff into a separate file.
+ Totally redid the callback stuff, now it's less awkward and supports C++ functions.
PortAudioCpp v19 revision 08 03/06/20:
mblaauw:
- Made deconstructors for Device and HostApi private.
+ Added a AsioDeviceWrapper host api specific device extension class.
- Refactored Exception into a Exception base class and PaException and PaCppException
derived classes.
- Added ASIO specific device info to the devs.cxx example.
- Fixed a bug in System::hostApiCount() and System::defaultHostApi().
+ Moved Device::null to System::nullDevice.
- Fixed some bugs in Device and System.
PortAudioCpp v19 revision 07 03/06/08:
mblaauw:
- Updated some doxy comments.
+ Renamed CbXyz to CallbackXyz.
+ Renamed all ``configurations'' to ``parameters''.
+ Renamed HalfDuplexStreamConfiguration to SingleDirectionStreamConfiguration.
- Renamed SingleDirectionStreamParameters::streamParameters() to
SingleDirectionStreamParameters::paSteamParameters.
- Added a non-constant version of SingleDirectionStreamParameters::paStreamParameters().
- A few improvements to SingleDirectionStreamParameters.
- Allowed AutoSystem to be created without initializing the System singleton
(using a ctor flag).
- Added a BlockingStream class (not implemented for now).
- Fixed many bugs in the implementation of the iterators.
- Fixed a bug in Device::operator==().
+ Added a C++ version of the patest_sine.c test/example.
- Added a ctor for StreamParameters for a default half-duplex stream.
- Added SingleDirectionStreamParameters::setDevice() and setNumChannels().
- Renamed System::numHostApis() to System::hostApiCount().
+ Rewrote the iterators and related classes. They are now fully STL compliant. The System now
has a static array of all HostApis and all Devices. Only the System can create HostApis and
Devices and they are non-copyable now. All HostApis and Devices are now passed by-reference.
- Renamed (System::) getVersion() to version() and getVersionText() to versionText().
- Renamed (Device::) numXyzChannels() to maxXyzChannels().
- Changed some stuff in StreamParameters.
+ Added a C++ version of the patest_devs.c test/example.
PortAudioCpp v19 revision 06 03/06/04:
mblaauw:
+ Added this file to the project (roughly, a `+' denotes a major change, a `-' a minor change).
- Added System::deviceByIndex(), useful when a Device's index is stored for instance.
- Renamed System::hostApiFromTypeId() to System::hostApiByTypeId().
- Updated and added some Doxygen documentation.
- Made Stream::usedIntputLatency(), Stream::usedOutputLatency() and
Stream::usedSampleRate() throw an paInternalError equivalent exception instead of paBadStreamPtr.
- Changed exception handling in Stream::open() functions. They now follow the PA error handling
mechanism better and a couple of bugs regarding ownership of objects were fixed.
- Renamed Device::isDefaultXyzDevice() to Device::isSystemDefaultXyzDevice().
- Added Device::isHostApiDefaultXyzDevice().
- Added StreamConfiguration::unsetFlag().
- Removed CUSTOM from SampleDataFormat.
- System::hostApiByTypeId() now throws an paInternalError if the type id was out-of-range; this
is a temporary work-around (see comments).
- Changed CbInterface to use paCallbackFun() instead of operator()().
- Renamed ``object'' to ``instance'' in CbMemFunAdapter.hxx.
- Added StreamConfiguration::setXyzHostApiSpecificSampleFormat().
- Added StreamConfiguration::isXyzSampleFormatHostApiSpecific().
- Changed error handling in System::terminate(), it can now throw an Exception.
- Added error handling in System::defaultHostApi().
- Added error handling in System::hostApisEnd().
- Changed some (but probably not all) C casts to C++ casts to avoid confusion with a
certain Python person.
- Renamed RaiiSystem to AutoSystem (class and file) as this is a come common convention.
- Renamed System::numDevices() to System::deviceCount() to be more compatible with PortAudio
(although PortAudio uses Pa_CountDevices() instead, see comment).
- Renamed HostApi::numDevices() to HostApi::deviceCount().
- Changed INC_ to INCLUDED_ in the header multiple include guards.
- Changed the order of functions in the StreamConfiguration class' header.
- Written some more info in PortAudioCpp.hxx (Doxygen).
- Added CallbackStream.hxx and CallbackStream.cxx files.
+ Refactored StreamConfiguration to remove the duplication which was there. There is now a
HalfDuplexStreamConfiguration class. Also made some improvements to these classes while
doing the refactoring.
+ Moved all code files to source/portaudiocpp/ and changed includes.
+ Moved all header files to include/portaudiocpp/ to easy a binary build if needed. The project
must be set to have .../include/ as a path to look for includes.
+ Refactored the Stream class into a Stream base class and a CallbackStream derived class.
- Renamed Stream::usingXyz() to Stream::xyz().
- Updated some doxy comments.
- Changed ``using namespace portaudio'' in .cxx files to ``namespace portaudio { ... }''.
PortAudioCpp v19 revision 05 03/04/09:
mblaauw:
- Initial release on the PortAudio mailinglist.

View file

@ -0,0 +1,44 @@
#ifndef INCLUDED_PORTAUDIO_ASIODEVICEADAPTER_HXX
#define INCLUDED_PORTAUDIO_ASIODEVICEADAPTER_HXX
namespace portaudio
{
// Forward declaration(s):
class Device;
// Declaration(s):
//////
/// @brief Adapts the given Device to an ASIO specific extension.
///
/// Deleting the AsioDeviceAdapter does not affect the underlying
/// Device.
//////
class AsioDeviceAdapter
{
public:
AsioDeviceAdapter(Device &device);
Device &device();
long minBufferSize() const;
long maxBufferSize() const;
long preferredBufferSize() const;
long granularity() const;
void showControlPanel(void *systemSpecific);
const char *inputChannelName(int channelIndex) const;
const char *outputChannelName(int channelIndex) const;
private:
Device *device_;
long minBufferSize_;
long maxBufferSize_;
long preferredBufferSize_;
long granularity_;
};
}
#endif // INCLUDED_PORTAUDIO_ASIODEVICEADAPTER_HXX

View file

@ -0,0 +1,62 @@
#ifndef INCLUDED_PORTAUDIO_AUTOSYSTEM_HXX
#define INCLUDED_PORTAUDIO_AUTOSYSTEM_HXX
// ---------------------------------------------------------------------------------------
#include "portaudiocpp/System.hxx"
// ---------------------------------------------------------------------------------------
namespace portaudio
{
//////
/// @brief A RAII idiom class to ensure automatic clean-up when an exception is
/// raised.
///
/// A simple helper class which uses the 'Resource Acquisition is Initialization'
/// idiom (RAII). Use this class to initialize/terminate the System rather than
/// using System directly. AutoSystem must be created on stack and must be valid
/// throughout the time you wish to use PortAudioCpp. Your 'main' function might be
/// a good place for it.
///
/// To avoid having to type portaudio::System::instance().xyz() all the time, it's usually
/// a good idea to make a reference to the System which can be accessed directly.
/// @verbatim
/// portaudio::AutoSys autoSys;
/// portaudio::System &sys = portaudio::System::instance();
/// @endverbatim
//////
class AutoSystem
{
public:
AutoSystem(bool initialize = true)
{
if (initialize)
System::initialize();
}
~AutoSystem()
{
if (System::exists())
System::terminate();
}
void initialize()
{
System::initialize();
}
void terminate()
{
System::terminate();
}
};
} // namespace portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_AUTOSYSTEM_HXX

View file

@ -0,0 +1,45 @@
#ifndef INCLUDED_PORTAUDIO_BLOCKINGSTREAM_HXX
#define INCLUDED_PORTAUDIO_BLOCKINGSTREAM_HXX
// ---------------------------------------------------------------------------------------
#include "portaudiocpp/Stream.hxx"
// ---------------------------------------------------------------------------------------
namespace portaudio
{
//////
/// @brief Stream class for blocking read/write-style input and output.
//////
class BlockingStream : public Stream
{
public:
BlockingStream();
BlockingStream(const StreamParameters &parameters);
~BlockingStream();
void open(const StreamParameters &parameters);
void read(void *buffer, unsigned long numFrames);
void write(const void *buffer, unsigned long numFrames);
signed long availableReadSize() const;
signed long availableWriteSize() const;
private:
BlockingStream(const BlockingStream &); // non-copyable
BlockingStream &operator=(const BlockingStream &); // non-copyable
};
} // portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_BLOCKINGSTREAM_HXX

View file

@ -0,0 +1,49 @@
#ifndef INCLUDED_PORTAUDIO_CFUNCALLBACKSTREAM_HXX
#define INCLUDED_PORTAUDIO_CFUNCALLBACKSTREAM_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
#include "portaudiocpp/CallbackStream.hxx"
// ---------------------------------------------------------------------------------------
// Forward declaration(s)
namespace portaudio
{
class StreamParameters;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
// -----------------------------------------------------------------------------------
//////
/// @brief Callback stream using a free function with C linkage. It's important that the function
/// the passed function pointer points to is declared ``extern "C"''.
//////
class CFunCallbackStream : public CallbackStream
{
public:
CFunCallbackStream();
CFunCallbackStream(const StreamParameters &parameters, PaStreamCallback *funPtr, void *userData);
~CFunCallbackStream();
void open(const StreamParameters &parameters, PaStreamCallback *funPtr, void *userData);
private:
CFunCallbackStream(const CFunCallbackStream &); // non-copyable
CFunCallbackStream &operator=(const CFunCallbackStream &); // non-copyable
};
// -----------------------------------------------------------------------------------
} // portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_MEMFUNCALLBACKSTREAM_HXX

View file

@ -0,0 +1,45 @@
#ifndef INCLUDED_PORTAUDIO_CALLBACKINTERFACE_HXX
#define INCLUDED_PORTAUDIO_CALLBACKINTERFACE_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
// ---------------------------------------------------------------------------------------
namespace portaudio
{
// -----------------------------------------------------------------------------------
//////
/// @brief Interface for an object that's callable as a PortAudioCpp callback object (ie that implements the
/// paCallbackFun method).
//////
class CallbackInterface
{
public:
virtual ~CallbackInterface() {}
virtual int paCallbackFun(const void *inputBuffer, void *outputBuffer, unsigned long numFrames,
const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags) = 0;
};
// -----------------------------------------------------------------------------------
namespace impl
{
extern "C"
{
int callbackInterfaceToPaCallbackAdapter(const void *inputBuffer, void *outputBuffer, unsigned long numFrames,
const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags,
void *userData);
} // extern "C"
}
// -----------------------------------------------------------------------------------
} // namespace portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_CALLBACKINTERFACE_HXX

View file

@ -0,0 +1,40 @@
#ifndef INCLUDED_PORTAUDIO_CALLBACKSTREAM_HXX
#define INCLUDED_PORTAUDIO_CALLBACKSTREAM_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
#include "portaudiocpp/Stream.hxx"
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
//////
/// @brief Base class for all Streams which use a callback-based mechanism.
//////
class CallbackStream : public Stream
{
protected:
CallbackStream();
virtual ~CallbackStream();
public:
// stream info (time-varying)
double cpuLoad() const;
private:
CallbackStream(const CallbackStream &); // non-copyable
CallbackStream &operator=(const CallbackStream &); // non-copyable
};
} // namespace portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_CALLBACKSTREAM_HXX

View file

@ -0,0 +1,86 @@
#ifndef INCLUDED_PORTAUDIO_CPPFUNCALLBACKSTREAM_HXX
#define INCLUDED_PORTAUDIO_CPPFUNCALLBACKSTREAM_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
#include "portaudiocpp/CallbackStream.hxx"
// ---------------------------------------------------------------------------------------
// Forward declaration(s):
namespace portaudio
{
class StreamParameters;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
namespace impl
{
extern "C"
{
int cppCallbackToPaCallbackAdapter(const void *inputBuffer, void *outputBuffer, unsigned long numFrames,
const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags,
void *userData);
} // extern "C"
}
// -----------------------------------------------------------------------------------
//////
/// @brief Callback stream using a C++ function (either a free function or a static function)
/// callback.
//////
class FunCallbackStream : public CallbackStream
{
public:
typedef int (*CallbackFunPtr)(const void *inputBuffer, void *outputBuffer, unsigned long numFrames,
const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags,
void *userData);
// -------------------------------------------------------------------------------
//////
/// @brief Simple structure containing a function pointer to the C++ callback function and a
/// (void) pointer to the user supplied data.
//////
struct CppToCCallbackData
{
CppToCCallbackData();
CppToCCallbackData(CallbackFunPtr funPtr, void *userData);
void init(CallbackFunPtr funPtr, void *userData);
CallbackFunPtr funPtr;
void *userData;
};
// -------------------------------------------------------------------------------
FunCallbackStream();
FunCallbackStream(const StreamParameters &parameters, CallbackFunPtr funPtr, void *userData);
~FunCallbackStream();
void open(const StreamParameters &parameters, CallbackFunPtr funPtr, void *userData);
private:
FunCallbackStream(const FunCallbackStream &); // non-copyable
FunCallbackStream &operator=(const FunCallbackStream &); // non-copyable
CppToCCallbackData adapterData_;
void open(const StreamParameters &parameters);
};
} // portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_CPPFUNCALLBACKSTREAM_HXX

View file

@ -0,0 +1,91 @@
#ifndef INCLUDED_PORTAUDIO_DEVICE_HXX
#define INCLUDED_PORTAUDIO_DEVICE_HXX
// ---------------------------------------------------------------------------------------
#include <iterator>
#include "portaudio.h"
#include "portaudiocpp/SampleDataFormat.hxx"
// ---------------------------------------------------------------------------------------
// Forward declaration(s):
namespace portaudio
{
class System;
class HostApi;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
//////
/// @brief Class which represents a PortAudio device in the System.
///
/// A single physical device in the system may have multiple PortAudio
/// Device representations using different HostApi 's though. A Device
/// can be half-duplex or full-duplex. A half-duplex Device can be used
/// to create a half-duplex Stream. A full-duplex Device can be used to
/// create a full-duplex Stream. If supported by the HostApi, two
/// half-duplex Devices can even be used to create a full-duplex Stream.
///
/// Note that Device objects are very light-weight and can be passed around
/// by-value.
//////
class Device
{
public:
// query info: name, max in channels, max out channels,
// default low/high input/output latency, default sample rate
PaDeviceIndex index() const;
const char *name() const;
int maxInputChannels() const;
int maxOutputChannels() const;
PaTime defaultLowInputLatency() const;
PaTime defaultHighInputLatency() const;
PaTime defaultLowOutputLatency() const;
PaTime defaultHighOutputLatency() const;
double defaultSampleRate() const;
bool isInputOnlyDevice() const; // extended
bool isOutputOnlyDevice() const; // extended
bool isFullDuplexDevice() const; // extended
bool isSystemDefaultInputDevice() const; // extended
bool isSystemDefaultOutputDevice() const; // extended
bool isHostApiDefaultInputDevice() const; // extended
bool isHostApiDefaultOutputDevice() const; // extended
bool operator==(const Device &rhs) const;
bool operator!=(const Device &rhs) const;
// host api reference
HostApi &hostApi();
const HostApi &hostApi() const;
private:
PaDeviceIndex index_;
const PaDeviceInfo *info_;
private:
friend class System;
explicit Device(PaDeviceIndex index);
~Device();
Device(const Device &); // non-copyable
Device &operator=(const Device &); // non-copyable
};
// -----------------------------------------------------------------------------------
} // namespace portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_DEVICE_HXX

View file

@ -0,0 +1,77 @@
#ifndef INCLUDED_PORTAUDIO_SINGLEDIRECTIONSTREAMPARAMETERS_HXX
#define INCLUDED_PORTAUDIO_SINGLEDIRECTIONSTREAMPARAMETERS_HXX
// ---------------------------------------------------------------------------------------
#include <cstddef>
#include "portaudio.h"
#include "portaudiocpp/System.hxx"
#include "portaudiocpp/SampleDataFormat.hxx"
// ---------------------------------------------------------------------------------------
// Forward declaration(s):
namespace portaudio
{
class Device;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
//////
/// @brief All parameters for one direction (either in or out) of a Stream. Together with
/// parameters common to both directions, two DirectionSpecificStreamParameters can make up
/// a StreamParameters object which contains all parameters for a Stream.
//////
class DirectionSpecificStreamParameters
{
public:
static DirectionSpecificStreamParameters null();
DirectionSpecificStreamParameters();
DirectionSpecificStreamParameters(const Device &device, int numChannels, SampleDataFormat format,
bool interleaved, PaTime suggestedLatency, void *hostApiSpecificStreamInfo);
// Set up methods:
void setDevice(const Device &device);
void setNumChannels(int numChannels);
void setSampleFormat(SampleDataFormat format, bool interleaved = true);
void setHostApiSpecificSampleFormat(PaSampleFormat format, bool interleaved = true);
void setSuggestedLatency(PaTime latency);
void setHostApiSpecificStreamInfo(void *streamInfo);
// Accessor methods:
PaStreamParameters *paStreamParameters();
const PaStreamParameters *paStreamParameters() const;
Device &device() const;
int numChannels() const;
SampleDataFormat sampleFormat() const;
bool isSampleFormatInterleaved() const;
bool isSampleFormatHostApiSpecific() const;
PaSampleFormat hostApiSpecificSampleFormat() const;
PaTime suggestedLatency() const;
void *hostApiSpecificStreamInfo() const;
private:
PaStreamParameters paStreamParameters_;
};
} // namespace portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_SINGLEDIRECTIONSTREAMPARAMETERS_HXX

View file

@ -0,0 +1,108 @@
#ifndef INCLUDED_PORTAUDIO_EXCEPTION_HXX
#define INCLUDED_PORTAUDIO_EXCEPTION_HXX
// ---------------------------------------------------------------------------------------
#include <exception>
#include "portaudio.h"
// ---------------------------------------------------------------------------------------
namespace portaudio
{
//////
/// @brief Base class for all exceptions PortAudioCpp can throw.
///
/// Class is derived from std::exception.
//////
class Exception : public std::exception
{
public:
virtual ~Exception() throw() {}
virtual const char *what() const throw() = 0;
};
// -----------------------------------------------------------------------------------
//////
/// @brief Wrapper for PortAudio error codes to C++ exceptions.
///
/// It wraps up PortAudio's error handling mechanism using
/// C++ exceptions and is derived from std::exception for
/// easy exception handling and to ease integration with
/// other code.
///
/// To know what exceptions each function may throw, look up
/// the errors that can occur in the PortAudio documentation
/// for the equivalent functions.
///
/// Some functions are likely to throw an exception (such as
/// Stream::open(), etc) and these should always be called in
/// try{} catch{} blocks and the thrown exceptions should be
/// handled properly (ie. the application shouldn't just abort,
/// but merely display a warning dialog to the user or something).
/// However nearly all functions in PortAudioCpp are capable
/// of throwing exceptions. When a function like Stream::isStopped()
/// throws an exception, it's such an exceptional state that it's
/// not likely that it can be recovered. PaExceptions such as these
/// can ``safely'' be left to be handled by some outer catch-all-like
/// mechanism for unrecoverable errors.
//////
class PaException : public Exception
{
public:
explicit PaException(PaError error);
const char *what() const throw();
PaError paError() const;
const char *paErrorText() const;
bool isHostApiError() const; // extended
long lastHostApiError() const;
const char *lastHostApiErrorText() const;
bool operator==(const PaException &rhs) const;
bool operator!=(const PaException &rhs) const;
private:
PaError error_;
};
// -----------------------------------------------------------------------------------
//////
/// @brief Exceptions specific to PortAudioCpp (ie. exceptions which do not have an
/// equivalent PortAudio error code).
//////
class PaCppException : public Exception
{
public:
enum ExceptionSpecifier
{
UNABLE_TO_ADAPT_DEVICE
};
PaCppException(ExceptionSpecifier specifier);
const char *what() const throw();
ExceptionSpecifier specifier() const;
bool operator==(const PaCppException &rhs) const;
bool operator!=(const PaCppException &rhs) const;
private:
ExceptionSpecifier specifier_;
};
} // namespace portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_EXCEPTION_HXX

View file

@ -0,0 +1,76 @@
#ifndef INCLUDED_PORTAUDIO_HOSTAPI_HXX
#define INCLUDED_PORTAUDIO_HOSTAPI_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
#include "portaudiocpp/System.hxx"
// ---------------------------------------------------------------------------------------
// Forward declaration(s):
namespace portaudio
{
class Device;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
//////
/// @brief HostApi represents a host API (usually type of driver) in the System.
///
/// A single System can support multiple HostApi's each one typically having
/// a set of Devices using that HostApi (usually driver type). All Devices in
/// the HostApi can be enumerated and the default input/output Device for this
/// HostApi can be retrieved.
//////
class HostApi
{
public:
typedef System::DeviceIterator DeviceIterator;
// query info: id, name, numDevices
PaHostApiTypeId typeId() const;
PaHostApiIndex index() const;
const char *name() const;
int deviceCount() const;
// iterate devices
DeviceIterator devicesBegin();
DeviceIterator devicesEnd();
// default devices
Device &defaultInputDevice() const;
Device &defaultOutputDevice() const;
// comparison operators
bool operator==(const HostApi &rhs) const;
bool operator!=(const HostApi &rhs) const;
private:
const PaHostApiInfo *info_;
Device **devices_;
private:
friend class System;
explicit HostApi(PaHostApiIndex index);
~HostApi();
HostApi(const HostApi &); // non-copyable
HostApi &operator=(const HostApi &); // non-copyable
};
}
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_HOSTAPI_HXX

View file

@ -0,0 +1,49 @@
#ifndef INCLUDED_PORTAUDIO_INTERFACECALLBACKSTREAM_HXX
#define INCLUDED_PORTAUDIO_INTERFACECALLBACKSTREAM_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
#include "portaudiocpp/CallbackStream.hxx"
// ---------------------------------------------------------------------------------------
// Forward declaration(s)
namespace portaudio
{
class StreamParameters;
class CallbackInterface;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
//////
/// @brief Callback stream using an instance of an object that's derived from the CallbackInterface
/// interface.
//////
class InterfaceCallbackStream : public CallbackStream
{
public:
InterfaceCallbackStream();
InterfaceCallbackStream(const StreamParameters &parameters, CallbackInterface &instance);
~InterfaceCallbackStream();
void open(const StreamParameters &parameters, CallbackInterface &instance);
private:
InterfaceCallbackStream(const InterfaceCallbackStream &); // non-copyable
InterfaceCallbackStream &operator=(const InterfaceCallbackStream &); // non-copyable
};
} // portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_INTERFACECALLBACKSTREAM_HXX

View file

@ -0,0 +1,107 @@
#ifndef INCLUDED_PORTAUDIO_MEMFUNCALLBACKSTREAM_HXX
#define INCLUDED_PORTAUDIO_MEMFUNCALLBACKSTREAM_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
#include "portaudiocpp/CallbackStream.hxx"
#include "portaudiocpp/CallbackInterface.hxx"
#include "portaudiocpp/StreamParameters.hxx"
#include "portaudiocpp/Exception.hxx"
#include "portaudiocpp/InterfaceCallbackStream.hxx"
// ---------------------------------------------------------------------------------------
namespace portaudio
{
//////
/// @brief Callback stream using a class's member function as a callback. Template argument T is the type of the
/// class of which a member function is going to be used.
///
/// Example usage:
/// @verbatim MemFunCallback<MyClass> stream = MemFunCallbackStream(parameters, *this, &MyClass::myCallbackFunction); @endverbatim
//////
template<typename T>
class MemFunCallbackStream : public CallbackStream
{
public:
typedef int (T::*CallbackFunPtr)(const void *, void *, unsigned long, const PaStreamCallbackTimeInfo *,
PaStreamCallbackFlags);
// -------------------------------------------------------------------------------
MemFunCallbackStream()
{
}
MemFunCallbackStream(const StreamParameters &parameters, T &instance, CallbackFunPtr memFun) : adapter_(instance, memFun)
{
open(parameters);
}
~MemFunCallbackStream()
{
close();
}
void open(const StreamParameters &parameters, T &instance, CallbackFunPtr memFun)
{
// XXX: need to check if already open?
adapter_.init(instance, memFun);
open(parameters);
}
private:
MemFunCallbackStream(const MemFunCallbackStream &); // non-copyable
MemFunCallbackStream &operator=(const MemFunCallbackStream &); // non-copyable
//////
/// @brief Inner class which adapts a member function callback to a CallbackInterface compliant
/// class (so it can be adapted using the paCallbackAdapter function).
//////
class MemFunToCallbackInterfaceAdapter : public CallbackInterface
{
public:
MemFunToCallbackInterfaceAdapter() {}
MemFunToCallbackInterfaceAdapter(T &instance, CallbackFunPtr memFun) : instance_(&instance), memFun_(memFun) {}
void init(T &instance, CallbackFunPtr memFun)
{
instance_ = &instance;
memFun_ = memFun;
}
int paCallbackFun(const void *inputBuffer, void *outputBuffer, unsigned long numFrames,
const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags)
{
return (instance_->*memFun_)(inputBuffer, outputBuffer, numFrames, timeInfo, statusFlags);
}
private:
T *instance_;
CallbackFunPtr memFun_;
};
MemFunToCallbackInterfaceAdapter adapter_;
void open(const StreamParameters &parameters)
{
PaError err = Pa_OpenStream(&stream_, parameters.inputParameters().paStreamParameters(), parameters.outputParameters().paStreamParameters(),
parameters.sampleRate(), parameters.framesPerBuffer(), parameters.flags(), &impl::callbackInterfaceToPaCallbackAdapter,
static_cast<void *>(&adapter_));
if (err != paNoError)
throw PaException(err);
}
};
} // portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_MEMFUNCALLBACKSTREAM_HXX

View file

@ -0,0 +1,109 @@
#ifndef INCLUDED_PORTAUDIO_PORTAUDIOCPP_HXX
#define INCLUDED_PORTAUDIO_PORTAUDIOCPP_HXX
// ---------------------------------------------------------------------------------------
//////
/// @mainpage PortAudioCpp
///
/// <h1>PortAudioCpp - A Native C++ Binding of PortAudio V19</h1>
/// <h2>PortAudio</h2>
/// <p>
/// PortAudio is a portable and mature C API for accessing audio hardware. It offers both callback-based and blocking
/// style input and output, deals with sample data format conversions, dithering and much more. There are a large number
/// of implementations available for various platforms including Windows MME, Windows DirectX, Windows and MacOS (Classic)
/// ASIO, MacOS Classic SoundManager, MacOS X CoreAudio, OSS (Linux), Linux ALSA, JACK (MacOS X and Linux) and SGI Irix
/// AL. Note that, currently not all of these implementations are equally complete or up-to-date (as PortAudio V19 is
/// still in development). Because PortAudio has a C API, it can easily be called from a variety of other programming
/// languages.
/// </p>
/// <h2>PortAudioCpp</h2>
/// <p>
/// Although, it is possible to use PortAudio's C API from within a C++ program, this is usually a little awkward
/// as procedural and object-oriented paradigms need to be mixed. PortAudioCpp aims to resolve this by encapsulating
/// PortAudio's C API to form an equivalent object-oriented C++ API. It provides a more natural integration of PortAudio
/// into C++ programs as well as a more structured interface. PortAudio's concepts were preserved as much as possible and
/// no additional features were added except for some `convenience methods'.
/// </p>
/// <p>
/// PortAudioCpp's main features are:
/// <ul>
/// <li>Structured object model.</li>
/// <li>C++ exception handling instead of C-style error return codes.</li>
/// <li>Handling of callbacks using free functions (C and C++), static functions, member functions or instances of classes
/// derived from a given interface.</li>
/// <li>STL compliant iterators to host APIs and devices.</li>
/// <li>Some additional convenience functions to more easily set up and use PortAudio.</li>
/// </ul>
/// </p>
/// <p>
/// PortAudioCpp requires a recent version of the PortAudio V19 source code. This can be obtained from CVS or as a snapshot
/// from the website. The examples also require the ASIO 2 SDK which can be obtained from the Steinberg website. Alternatively, the
/// examples can easily be modified to compile without needing ASIO.
/// </p>
/// <p>
/// Supported platforms:
/// <ul>
/// <li>Microsoft Visual C++ 6.0, 7.0 (.NET 2002) and 7.1 (.NET 2003).</li>
/// <li>GNU G++ 2.95 and G++ 3.3.</li>
/// </ul>
/// Other platforms should be easily supported as PortAudioCpp is platform-independent and (reasonably) C++ standard compliant.
/// </p>
/// <p>
/// This documentation mainly provides information specific to PortAudioCpp. For a more complete explanation of all of the
/// concepts used, please consult the PortAudio documentation.
/// </p>
/// <p>
/// PortAudioCpp was developed by Merlijn Blaauw with many great suggestions and help from Ross Bencina. Ludwig Schwardt provided
/// GNU/Linux build files and checked G++ compatibility. PortAudioCpp may be used under the same licensing, conditions and
/// warranty as PortAudio. See <a href="http://www.portaudio.com/license.html">the PortAudio license</a> for more details.
/// </p>
/// <h2>Links</h2>
/// <p>
/// <a href="http://www.portaudio.com/">Official PortAudio site.</a><br>
/// </p>
//////
// ---------------------------------------------------------------------------------------
//////
/// @namespace portaudio
///
/// To avoid name collision, everything in PortAudioCpp is in the portaudio
/// namespace. If this name is too long it's usually pretty safe to use an
/// alias like ``namespace pa = portaudio;''.
//////
// ---------------------------------------------------------------------------------------
//////
/// @file PortAudioCpp.hxx
/// An include-all header file (for lazy programmers and using pre-compiled headers).
//////
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
#include "portaudiocpp/AutoSystem.hxx"
#include "portaudiocpp/BlockingStream.hxx"
#include "portaudiocpp/CallbackInterface.hxx"
#include "portaudiocpp/CallbackStream.hxx"
#include "portaudiocpp/CFunCallbackStream.hxx"
#include "portaudiocpp/CppFunCallbackStream.hxx"
#include "portaudiocpp/Device.hxx"
#include "portaudiocpp/Exception.hxx"
#include "portaudiocpp/HostApi.hxx"
#include "portaudiocpp/InterfaceCallbackStream.hxx"
#include "portaudiocpp/MemFunCallbackStream.hxx"
#include "portaudiocpp/SampleDataFormat.hxx"
#include "portaudiocpp/DirectionSpecificStreamParameters.hxx"
#include "portaudiocpp/Stream.hxx"
#include "portaudiocpp/StreamParameters.hxx"
#include "portaudiocpp/System.hxx"
#include "portaudiocpp/SystemDeviceIterator.hxx"
#include "portaudiocpp/SystemHostApiIterator.hxx"
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_PORTAUDIOCPP_HXX

View file

@ -0,0 +1,35 @@
#ifndef INCLUDED_PORTAUDIO_SAMPLEDATAFORMAT_HXX
#define INCLUDED_PORTAUDIO_SAMPLEDATAFORMAT_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
// ---------------------------------------------------------------------------------------
namespace portaudio
{
//////
/// @brief PortAudio sample data formats.
///
/// Small helper enum to wrap the PortAudio defines.
//////
enum SampleDataFormat
{
INVALID_FORMAT = 0,
FLOAT32 = paFloat32,
INT32 = paInt32,
INT24 = paInt24,
INT16 = paInt16,
INT8 = paInt8,
UINT8 = paUInt8
};
} // namespace portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_SAMPLEDATAFORMAT_HXX

View file

@ -0,0 +1,82 @@
#ifndef INCLUDED_PORTAUDIO_STREAM_HXX
#define INCLUDED_PORTAUDIO_STREAM_HXX
#include "portaudio.h"
// ---------------------------------------------------------------------------------------
// Forward declaration(s):
namespace portaudio
{
class StreamParameters;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
//////
/// @brief A Stream represents an active or inactive input and/or output data
/// stream in the System.
///
/// Concrete Stream classes should ensure themselves being in a closed state at
/// destruction (i.e. by calling their own close() method in their deconstructor).
/// Following good C++ programming practices, care must be taken to ensure no
/// exceptions are thrown by the deconstructor of these classes. As a consequence,
/// clients need to explicitly call close() to ensure the stream closed successfully.
///
/// The Stream object can be used to manipulate the Stream's state. Also, time-constant
/// and time-varying information about the Stream can be retrieved.
//////
class Stream
{
public:
// Opening/closing:
virtual ~Stream();
virtual void close();
bool isOpen() const;
// Additional set up:
void setStreamFinishedCallback(PaStreamFinishedCallback *callback);
// State management:
void start();
void stop();
void abort();
bool isStopped() const;
bool isActive() const;
// Stream info (time-constant, but might become time-variant soon):
PaTime inputLatency() const;
PaTime outputLatency() const;
double sampleRate() const;
// Stream info (time-varying):
PaTime time() const;
// Accessors for PortAudio PaStream, useful for interfacing
// with PortAudio add-ons (such as PortMixer) for instance:
const PaStream *paStream() const;
PaStream *paStream();
protected:
Stream(); // abstract class
PaStream *stream_;
private:
Stream(const Stream &); // non-copyable
Stream &operator=(const Stream &); // non-copyable
};
} // namespace portaudio
#endif // INCLUDED_PORTAUDIO_STREAM_HXX

View file

@ -0,0 +1,77 @@
#ifndef INCLUDED_PORTAUDIO_STREAMPARAMETERS_HXX
#define INCLUDED_PORTAUDIO_STREAMPARAMETERS_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
#include "portaudiocpp/DirectionSpecificStreamParameters.hxx"
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
//////
/// @brief The entire set of parameters needed to configure and open
/// a Stream.
///
/// It contains parameters of input, output and shared parameters.
/// Using the isSupported() method, the StreamParameters can be
/// checked if opening a Stream using this StreamParameters would
/// succeed or not. Accessors are provided to higher-level parameters
/// aswell as the lower-level parameters which are mainly intended for
/// internal use.
//////
class StreamParameters
{
public:
StreamParameters();
StreamParameters(const DirectionSpecificStreamParameters &inputParameters,
const DirectionSpecificStreamParameters &outputParameters, double sampleRate,
unsigned long framesPerBuffer, PaStreamFlags flags);
// Set up for direction-specific:
void setInputParameters(const DirectionSpecificStreamParameters &parameters);
void setOutputParameters(const DirectionSpecificStreamParameters &parameters);
// Set up for common parameters:
void setSampleRate(double sampleRate);
void setFramesPerBuffer(unsigned long framesPerBuffer);
void setFlag(PaStreamFlags flag);
void unsetFlag(PaStreamFlags flag);
void clearFlags();
// Validation:
bool isSupported() const;
// Accessors (direction-specific):
DirectionSpecificStreamParameters &inputParameters();
const DirectionSpecificStreamParameters &inputParameters() const;
DirectionSpecificStreamParameters &outputParameters();
const DirectionSpecificStreamParameters &outputParameters() const;
// Accessors (common):
double sampleRate() const;
unsigned long framesPerBuffer() const;
PaStreamFlags flags() const;
bool isFlagSet(PaStreamFlags flag) const;
private:
// Half-duplex specific parameters:
DirectionSpecificStreamParameters inputParameters_;
DirectionSpecificStreamParameters outputParameters_;
// Common parameters:
double sampleRate_;
unsigned long framesPerBuffer_;
PaStreamFlags flags_;
};
} // namespace portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_STREAMPARAMETERS_HXX

View file

@ -0,0 +1,107 @@
#ifndef INCLUDED_PORTAUDIO_SYSTEM_HXX
#define INCLUDED_PORTAUDIO_SYSTEM_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
// ---------------------------------------------------------------------------------------
// Forward declaration(s):
namespace portaudio
{
class Device;
class Stream;
class HostApi;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
//////
/// @brief System singleton which represents the PortAudio system.
///
/// The System is used to initialize/terminate PortAudio and provide
/// a single access point to the PortAudio System (instance()).
/// It can be used to iterate through all HostApi 's in the System as
/// well as all devices in the System. It also provides some utility
/// functionality of PortAudio.
///
/// Terminating the System will also abort and close the open streams.
/// The Stream objects will need to be deallocated by the client though
/// (it's usually a good idea to have them cleaned up automatically).
//////
class System
{
public:
class HostApiIterator; // forward declaration
class DeviceIterator; // forward declaration
// -------------------------------------------------------------------------------
static int version();
static const char *versionText();
static void initialize();
static void terminate();
static System &instance();
static bool exists();
// -------------------------------------------------------------------------------
// host apis:
HostApiIterator hostApisBegin();
HostApiIterator hostApisEnd();
HostApi &defaultHostApi();
HostApi &hostApiByTypeId(PaHostApiTypeId type);
HostApi &hostApiByIndex(PaHostApiIndex index);
int hostApiCount();
// -------------------------------------------------------------------------------
// devices:
DeviceIterator devicesBegin();
DeviceIterator devicesEnd();
Device &defaultInputDevice();
Device &defaultOutputDevice();
Device &deviceByIndex(PaDeviceIndex index);
int deviceCount();
static Device &nullDevice();
// -------------------------------------------------------------------------------
// misc:
void sleep(long msec);
int sizeOfSample(PaSampleFormat format);
private:
System();
~System();
static System *instance_;
static int initCount_;
static HostApi **hostApis_;
static Device **devices_;
static Device *nullDevice_;
};
} // namespace portaudio
#endif // INCLUDED_PORTAUDIO_SYSTEM_HXX

View file

@ -0,0 +1,66 @@
#ifndef INCLUDED_PORTAUDIO_SYSTEMDEVICEITERATOR_HXX
#define INCLUDED_PORTAUDIO_SYSTEMDEVICEITERATOR_HXX
// ---------------------------------------------------------------------------------------
#include <iterator>
#include <cstddef>
#include "portaudiocpp/System.hxx"
// ---------------------------------------------------------------------------------------
// Forward declaration(s):
namespace portaudio
{
class Device;
class HostApi;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
//////
/// @brief Iterator class for iterating through all Devices in a System.
///
/// Devices will be iterated by iterating all Devices in each
/// HostApi in the System. Compliant with the STL bidirectional
/// iterator concept.
//////
class System::DeviceIterator
{
public:
typedef std::bidirectional_iterator_tag iterator_category;
typedef Device value_type;
typedef ptrdiff_t difference_type;
typedef Device * pointer;
typedef Device & reference;
Device &operator*() const;
Device *operator->() const;
DeviceIterator &operator++();
DeviceIterator operator++(int);
DeviceIterator &operator--();
DeviceIterator operator--(int);
bool operator==(const DeviceIterator &rhs) const;
bool operator!=(const DeviceIterator &rhs) const;
private:
friend class System;
friend class HostApi;
Device **ptr_;
};
} // namespace portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_SYSTEMDEVICEITERATOR_HXX

View file

@ -0,0 +1,61 @@
#ifndef INCLUDED_PORTAUDIO_SYSTEMHOSTAPIITERATOR_HXX
#define INCLUDED_PORTAUDIO_SYSTEMHOSTAPIITERATOR_HXX
// ---------------------------------------------------------------------------------------
#include <iterator>
#include <cstddef>
#include "portaudiocpp/System.hxx"
// ---------------------------------------------------------------------------------------
// Forward declaration(s):
namespace portaudio
{
class HostApi;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
//////
/// @brief Iterator class for iterating through all HostApis in a System.
///
/// Compliant with the STL bidirectional iterator concept.
//////
class System::HostApiIterator
{
public:
typedef std::bidirectional_iterator_tag iterator_category;
typedef Device value_type;
typedef ptrdiff_t difference_type;
typedef HostApi * pointer;
typedef HostApi & reference;
HostApi &operator*() const;
HostApi *operator->() const;
HostApiIterator &operator++();
HostApiIterator operator++(int);
HostApiIterator &operator--();
HostApiIterator operator--(int);
bool operator==(const HostApiIterator &rhs) const;
bool operator!=(const HostApiIterator &rhs) const;
private:
friend class System;
HostApi **ptr_;
};
} // namespace portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_SYSTEMHOSTAPIITERATOR_HXX

View file

@ -0,0 +1,83 @@
#include "portaudiocpp/AsioDeviceAdapter.hxx"
#include "portaudio.h"
#include "pa_asio.h"
#include "portaudiocpp/Device.hxx"
#include "portaudiocpp/HostApi.hxx"
#include "portaudiocpp/Exception.hxx"
namespace portaudio
{
AsioDeviceAdapter::AsioDeviceAdapter(Device &device)
{
if (device.hostApi().typeId() != paASIO)
throw PaCppException(PaCppException::UNABLE_TO_ADAPT_DEVICE);
device_ = &device;
PaError err = PaAsio_GetAvailableLatencyValues(device_->index(), &minBufferSize_, &maxBufferSize_,
&preferredBufferSize_, &granularity_);
if (err != paNoError)
throw PaException(err);
}
Device &AsioDeviceAdapter::device()
{
return *device_;
}
long AsioDeviceAdapter::minBufferSize() const
{
return minBufferSize_;
}
long AsioDeviceAdapter::maxBufferSize() const
{
return maxBufferSize_;
}
long AsioDeviceAdapter::preferredBufferSize() const
{
return preferredBufferSize_;
}
long AsioDeviceAdapter::granularity() const
{
return granularity_;
}
void AsioDeviceAdapter::showControlPanel(void *systemSpecific)
{
PaError err = PaAsio_ShowControlPanel(device_->index(), systemSpecific);
if (err != paNoError)
throw PaException(err);
}
const char *AsioDeviceAdapter::inputChannelName(int channelIndex) const
{
const char *channelName;
PaError err = PaAsio_GetInputChannelName(device_->index(), channelIndex, &channelName);
if (err != paNoError)
throw PaException(err);
return channelName;
}
const char *AsioDeviceAdapter::outputChannelName(int channelIndex) const
{
const char *channelName;
PaError err = PaAsio_GetOutputChannelName(device_->index(), channelIndex, &channelName);
if (err != paNoError)
throw PaException(err);
return channelName;
}
}

View file

@ -0,0 +1,100 @@
#include "portaudiocpp/BlockingStream.hxx"
#include "portaudio.h"
#include "portaudiocpp/StreamParameters.hxx"
#include "portaudiocpp/Exception.hxx"
namespace portaudio
{
// --------------------------------------------------------------------------------------
BlockingStream::BlockingStream()
{
}
BlockingStream::BlockingStream(const StreamParameters &parameters)
{
open(parameters);
}
BlockingStream::~BlockingStream()
{
try
{
close();
}
catch (...)
{
// ignore all errors
}
}
// --------------------------------------------------------------------------------------
void BlockingStream::open(const StreamParameters &parameters)
{
PaError err = Pa_OpenStream(&stream_, parameters.inputParameters().paStreamParameters(), parameters.outputParameters().paStreamParameters(),
parameters.sampleRate(), parameters.framesPerBuffer(), parameters.flags(), NULL, NULL);
if (err != paNoError)
{
throw PaException(err);
}
}
// --------------------------------------------------------------------------------------
void BlockingStream::read(void *buffer, unsigned long numFrames)
{
PaError err = Pa_ReadStream(stream_, buffer, numFrames);
if (err != paNoError)
{
throw PaException(err);
}
}
void BlockingStream::write(const void *buffer, unsigned long numFrames)
{
PaError err = Pa_WriteStream(stream_, buffer, numFrames);
if (err != paNoError)
{
throw PaException(err);
}
}
// --------------------------------------------------------------------------------------
signed long BlockingStream::availableReadSize() const
{
signed long avail = Pa_GetStreamReadAvailable(stream_);
if (avail < 0)
{
throw PaException(avail);
}
return avail;
}
signed long BlockingStream::availableWriteSize() const
{
signed long avail = Pa_GetStreamWriteAvailable(stream_);
if (avail < 0)
{
throw PaException(avail);
}
return avail;
}
// --------------------------------------------------------------------------------------
} // portaudio

View file

@ -0,0 +1,41 @@
#include "portaudiocpp/CFunCallbackStream.hxx"
#include "portaudiocpp/StreamParameters.hxx"
#include "portaudiocpp/Exception.hxx"
namespace portaudio
{
CFunCallbackStream::CFunCallbackStream()
{
}
CFunCallbackStream::CFunCallbackStream(const StreamParameters &parameters, PaStreamCallback *funPtr, void *userData)
{
open(parameters, funPtr, userData);
}
CFunCallbackStream::~CFunCallbackStream()
{
try
{
close();
}
catch (...)
{
// ignore all errors
}
}
// ---------------------------------------------------------------------------------==
void CFunCallbackStream::open(const StreamParameters &parameters, PaStreamCallback *funPtr, void *userData)
{
PaError err = Pa_OpenStream(&stream_, parameters.inputParameters().paStreamParameters(), parameters.outputParameters().paStreamParameters(),
parameters.sampleRate(), parameters.framesPerBuffer(), parameters.flags(), funPtr, userData);
if (err != paNoError)
{
throw PaException(err);
}
}
}

View file

@ -0,0 +1,25 @@
#include "portaudiocpp/CallbackInterface.hxx"
namespace portaudio
{
namespace impl
{
//////
/// Adapts any CallbackInterface object to a C-callable function (ie this function). A
/// pointer to the object should be passed as ``userData'' when setting up the callback.
//////
int callbackInterfaceToPaCallbackAdapter(const void *inputBuffer, void *outputBuffer, unsigned long numFrames,
const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData)
{
CallbackInterface *cb = static_cast<CallbackInterface *>(userData);
return cb->paCallbackFun(inputBuffer, outputBuffer, numFrames, timeInfo, statusFlags);
}
} // namespace impl
} // namespace portaudio

View file

@ -0,0 +1,20 @@
#include "portaudiocpp/CallbackStream.hxx"
namespace portaudio
{
CallbackStream::CallbackStream()
{
}
CallbackStream::~CallbackStream()
{
}
// -----------------------------------------------------------------------------------
double CallbackStream::cpuLoad() const
{
return Pa_GetStreamCpuLoad(stream_);
}
} // namespace portaudio

View file

@ -0,0 +1,81 @@
#include "portaudiocpp/CppFunCallbackStream.hxx"
#include "portaudiocpp/StreamParameters.hxx"
#include "portaudiocpp/Exception.hxx"
namespace portaudio
{
namespace impl
{
//////
/// Adapts any a C++ callback to a C-callable function (ie this function). A
/// pointer to a struct with the C++ function pointer and the actual user data should be
/// passed as the ``userData'' parameter when setting up the callback.
//////
int cppCallbackToPaCallbackAdapter(const void *inputBuffer, void *outputBuffer, unsigned long numFrames,
const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData)
{
FunCallbackStream::CppToCCallbackData *data = static_cast<FunCallbackStream::CppToCCallbackData *>(userData);
return data->funPtr(inputBuffer, outputBuffer, numFrames, timeInfo, statusFlags, data->userData);
}
}
// -----------------------------------------------------------------------------------
FunCallbackStream::CppToCCallbackData::CppToCCallbackData()
{
}
FunCallbackStream::CppToCCallbackData::CppToCCallbackData(CallbackFunPtr funPtr, void *userData) : funPtr(funPtr), userData(userData)
{
}
void FunCallbackStream::CppToCCallbackData::init(CallbackFunPtr funPtr, void *userData)
{
this->funPtr = funPtr;
this->userData = userData;
}
// -----------------------------------------------------------------------------------
FunCallbackStream::FunCallbackStream()
{
}
FunCallbackStream::FunCallbackStream(const StreamParameters &parameters, CallbackFunPtr funPtr, void *userData) : adapterData_(funPtr, userData)
{
open(parameters);
}
FunCallbackStream::~FunCallbackStream()
{
try
{
close();
}
catch (...)
{
// ignore all errors
}
}
void FunCallbackStream::open(const StreamParameters &parameters, CallbackFunPtr funPtr, void *userData)
{
adapterData_.init(funPtr, userData);
open(parameters);
}
void FunCallbackStream::open(const StreamParameters &parameters)
{
PaError err = Pa_OpenStream(&stream_, parameters.inputParameters().paStreamParameters(), parameters.outputParameters().paStreamParameters(),
parameters.sampleRate(), parameters.framesPerBuffer(), parameters.flags(), &impl::cppCallbackToPaCallbackAdapter,
static_cast<void *>(&adapterData_));
if (err != paNoError)
{
throw PaException(err);
}
}
// -----------------------------------------------------------------------------------
}

View file

@ -0,0 +1,168 @@
#include "portaudiocpp/Device.hxx"
#include <cstddef>
#include "portaudiocpp/HostApi.hxx"
#include "portaudiocpp/System.hxx"
#include "portaudiocpp/Exception.hxx"
namespace portaudio
{
// -------------------------------------------------------------------------------
Device::Device(PaDeviceIndex index) : index_(index)
{
if (index == paNoDevice)
info_ = NULL;
else
info_ = Pa_GetDeviceInfo(index);
}
Device::~Device()
{
}
PaDeviceIndex Device::index() const
{
return index_;
}
const char *Device::name() const
{
if (info_ == NULL)
return "";
return info_->name;
}
int Device::maxInputChannels() const
{
if (info_ == NULL)
return 0;
return info_->maxInputChannels;
}
int Device::maxOutputChannels() const
{
if (info_ == NULL)
return 0;
return info_->maxOutputChannels;
}
PaTime Device::defaultLowInputLatency() const
{
if (info_ == NULL)
return static_cast<PaTime>(0.0);
return info_->defaultLowInputLatency;
}
PaTime Device::defaultHighInputLatency() const
{
if (info_ == NULL)
return static_cast<PaTime>(0.0);
return info_->defaultHighInputLatency;
}
PaTime Device::defaultLowOutputLatency() const
{
if (info_ == NULL)
return static_cast<PaTime>(0.0);
return info_->defaultLowOutputLatency;
}
PaTime Device::defaultHighOutputLatency() const
{
if (info_ == NULL)
return static_cast<PaTime>(0.0);
return info_->defaultHighOutputLatency;
}
double Device::defaultSampleRate() const
{
if (info_ == NULL)
return 0.0;
return info_->defaultSampleRate;
}
// -------------------------------------------------------------------------------
bool Device::isInputOnlyDevice() const
{
return (maxOutputChannels() == 0);
}
bool Device::isOutputOnlyDevice() const
{
return (maxInputChannels() == 0);
}
bool Device::isFullDuplexDevice() const
{
return (maxInputChannels() > 0 && maxOutputChannels() > 0);
}
bool Device::isSystemDefaultInputDevice() const
{
return (System::instance().defaultInputDevice() == *this);
}
bool Device::isSystemDefaultOutputDevice() const
{
return (System::instance().defaultOutputDevice() == *this);
}
bool Device::isHostApiDefaultInputDevice() const
{
return (hostApi().defaultInputDevice() == *this);
}
bool Device::isHostApiDefaultOutputDevice() const
{
return (hostApi().defaultOutputDevice() == *this);
}
// -------------------------------------------------------------------------------
bool Device::operator==(const Device &rhs) const
{
return (index_ == rhs.index_);
}
bool Device::operator!=(const Device &rhs) const
{
return !(*this == rhs);
}
// -------------------------------------------------------------------------------
HostApi &Device::hostApi()
{
// NOTE: will cause an exception when called for the null device
if (info_ == NULL)
throw PaException(paInternalError);
return System::instance().hostApiByIndex(info_->hostApi);
}
const HostApi &Device::hostApi() const
{
// NOTE; will cause an exception when called for the null device
if (info_ == NULL)
throw PaException(paInternalError);
return System::instance().hostApiByIndex(info_->hostApi);
}
// -------------------------------------------------------------------------------
} // namespace portaudio

View file

@ -0,0 +1,163 @@
#include "portaudiocpp/DirectionSpecificStreamParameters.hxx"
#include "portaudiocpp/Device.hxx"
namespace portaudio
{
// -----------------------------------------------------------------------------------
//////
/// Returns a `nil' DirectionSpecificStreamParameters object. This can be used to
/// specify that one direction of a Stream is not required (i.e. when creating
/// a half-duplex Stream). All fields of the null DirectionSpecificStreamParameters
/// object are invalid except for the device and the number of channel, which are set
/// to paNoDevice and 0 respectively.
//////
DirectionSpecificStreamParameters DirectionSpecificStreamParameters::null()
{
DirectionSpecificStreamParameters tmp;
tmp.paStreamParameters_.device = paNoDevice;
tmp.paStreamParameters_.channelCount = 0;
return tmp;
}
// -----------------------------------------------------------------------------------
//////
/// Default constructor -- all parameters will be uninitialized.
//////
DirectionSpecificStreamParameters::DirectionSpecificStreamParameters()
{
}
//////
/// Constructor which sets all required fields.
//////
DirectionSpecificStreamParameters::DirectionSpecificStreamParameters(const Device &device, int numChannels,
SampleDataFormat format, bool interleaved, PaTime suggestedLatency, void *hostApiSpecificStreamInfo)
{
setDevice(device);
setNumChannels(numChannels);
setSampleFormat(format, interleaved);
setSuggestedLatency(suggestedLatency);
setHostApiSpecificStreamInfo(hostApiSpecificStreamInfo);
}
// -----------------------------------------------------------------------------------
void DirectionSpecificStreamParameters::setDevice(const Device &device)
{
paStreamParameters_.device = device.index();
}
void DirectionSpecificStreamParameters::setNumChannels(int numChannels)
{
paStreamParameters_.channelCount = numChannels;
}
void DirectionSpecificStreamParameters::setSampleFormat(SampleDataFormat format, bool interleaved)
{
paStreamParameters_.sampleFormat = static_cast<PaSampleFormat>(format);
if (!interleaved)
paStreamParameters_.sampleFormat |= paNonInterleaved;
}
void DirectionSpecificStreamParameters::setHostApiSpecificSampleFormat(PaSampleFormat format, bool interleaved)
{
paStreamParameters_.sampleFormat = format;
paStreamParameters_.sampleFormat |= paCustomFormat;
if (!interleaved)
paStreamParameters_.sampleFormat |= paNonInterleaved;
}
void DirectionSpecificStreamParameters::setSuggestedLatency(PaTime latency)
{
paStreamParameters_.suggestedLatency = latency;
}
void DirectionSpecificStreamParameters::setHostApiSpecificStreamInfo(void *streamInfo)
{
paStreamParameters_.hostApiSpecificStreamInfo = streamInfo;
}
// -----------------------------------------------------------------------------------
PaStreamParameters *DirectionSpecificStreamParameters::paStreamParameters()
{
if (paStreamParameters_.channelCount > 0 && paStreamParameters_.device != paNoDevice)
return &paStreamParameters_;
else
return NULL;
}
const PaStreamParameters *DirectionSpecificStreamParameters::paStreamParameters() const
{
if (paStreamParameters_.channelCount > 0 && paStreamParameters_.device != paNoDevice)
return &paStreamParameters_;
else
return NULL;
}
Device &DirectionSpecificStreamParameters::device() const
{
return System::instance().deviceByIndex(paStreamParameters_.device);
}
int DirectionSpecificStreamParameters::numChannels() const
{
return paStreamParameters_.channelCount;
}
//////
/// Returns the (non host api-specific) sample format, without including
/// the paNonInterleaved flag. If the sample format is host api-spefific,
/// INVALID_FORMAT (0) will be returned.
//////
SampleDataFormat DirectionSpecificStreamParameters::sampleFormat() const
{
if (isSampleFormatHostApiSpecific())
return INVALID_FORMAT;
else
return static_cast<SampleDataFormat>(paStreamParameters_.sampleFormat & ~paNonInterleaved);
}
bool DirectionSpecificStreamParameters::isSampleFormatInterleaved() const
{
return ((paStreamParameters_.sampleFormat & paNonInterleaved) == 0);
}
bool DirectionSpecificStreamParameters::isSampleFormatHostApiSpecific() const
{
return ((paStreamParameters_.sampleFormat & paCustomFormat) == 0);
}
//////
/// Returns the host api-specific sample format, without including any
/// paCustomFormat or paNonInterleaved flags. Will return 0 if the sample format is
/// not host api-specific.
//////
PaSampleFormat DirectionSpecificStreamParameters::hostApiSpecificSampleFormat() const
{
if (isSampleFormatHostApiSpecific())
return paStreamParameters_.sampleFormat & ~paCustomFormat & ~paNonInterleaved;
else
return 0;
}
PaTime DirectionSpecificStreamParameters::suggestedLatency() const
{
return paStreamParameters_.suggestedLatency;
}
void *DirectionSpecificStreamParameters::hostApiSpecificStreamInfo() const
{
return paStreamParameters_.hostApiSpecificStreamInfo;
}
// -----------------------------------------------------------------------------------
} // namespace portaudio

View file

@ -0,0 +1,123 @@
#include "portaudiocpp/Exception.hxx"
namespace portaudio
{
// -----------------------------------------------------------------------------------
// PaException:
// -----------------------------------------------------------------------------------
//////
/// Wraps a PortAudio error into a PortAudioCpp PaException.
//////
PaException::PaException(PaError error) : error_(error)
{
}
// -----------------------------------------------------------------------------------
//////
/// Alias for paErrorText(), to have std::exception compliance.
//////
const char *PaException::what() const throw()
{
return paErrorText();
}
// -----------------------------------------------------------------------------------
//////
/// Returns the PortAudio error code (PaError).
//////
PaError PaException::paError() const
{
return error_;
}
//////
/// Returns the error as a (zero-terminated) text string.
//////
const char *PaException::paErrorText() const
{
return Pa_GetErrorText(error_);
}
//////
/// Returns true is the error is a HostApi error.
//////
bool PaException::isHostApiError() const
{
return (error_ == paUnanticipatedHostError);
}
//////
/// Returns the last HostApi error (which is the current one if
/// isHostApiError() returns true) as an error code.
//////
long PaException::lastHostApiError() const
{
return Pa_GetLastHostErrorInfo()->errorCode;
}
//////
/// Returns the last HostApi error (which is the current one if
/// isHostApiError() returns true) as a (zero-terminated) text
/// string, if it's available.
//////
const char *PaException::lastHostApiErrorText() const
{
return Pa_GetLastHostErrorInfo()->errorText;
}
// -----------------------------------------------------------------------------------
bool PaException::operator==(const PaException &rhs) const
{
return (error_ == rhs.error_);
}
bool PaException::operator!=(const PaException &rhs) const
{
return !(*this == rhs);
}
// -----------------------------------------------------------------------------------
// PaCppException:
// -----------------------------------------------------------------------------------
PaCppException::PaCppException(ExceptionSpecifier specifier) : specifier_(specifier)
{
}
const char *PaCppException::what() const throw()
{
switch (specifier_)
{
case UNABLE_TO_ADAPT_DEVICE:
{
return "Unable to adapt the given device to the specified host api specific device extension";
}
}
return "Unknown exception";
}
PaCppException::ExceptionSpecifier PaCppException::specifier() const
{
return specifier_;
}
bool PaCppException::operator==(const PaCppException &rhs) const
{
return (specifier_ == rhs.specifier_);
}
bool PaCppException::operator!=(const PaCppException &rhs) const
{
return !(*this == rhs);
}
// -----------------------------------------------------------------------------------
} // namespace portaudio

View file

@ -0,0 +1,121 @@
#include "portaudiocpp/HostApi.hxx"
#include "portaudiocpp/System.hxx"
#include "portaudiocpp/Device.hxx"
#include "portaudiocpp/SystemDeviceIterator.hxx"
#include "portaudiocpp/Exception.hxx"
namespace portaudio
{
// -----------------------------------------------------------------------------------
HostApi::HostApi(PaHostApiIndex index) : devices_(NULL)
{
try
{
info_ = Pa_GetHostApiInfo(index);
// Create and populate devices array:
int numDevices = deviceCount();
devices_ = new Device*[numDevices];
for (int i = 0; i < numDevices; ++i)
{
PaDeviceIndex deviceIndex = Pa_HostApiDeviceIndexToDeviceIndex(index, i);
if (deviceIndex < 0)
{
throw PaException(deviceIndex);
}
devices_[i] = &System::instance().deviceByIndex(deviceIndex);
}
}
catch (const std::exception &e)
{
// Delete any (partially) constructed objects (deconstructor isn't called):
delete[] devices_; // devices_ is either NULL or valid
// Re-throw exception:
throw e;
}
}
HostApi::~HostApi()
{
// Destroy devices array:
delete[] devices_;
}
// -----------------------------------------------------------------------------------
PaHostApiTypeId HostApi::typeId() const
{
return info_->type;
}
PaHostApiIndex HostApi::index() const
{
PaHostApiIndex index = Pa_HostApiTypeIdToHostApiIndex(typeId());
if (index < 0)
throw PaException(index);
return index;
}
const char *HostApi::name() const
{
return info_->name;
}
int HostApi::deviceCount() const
{
return info_->deviceCount;
}
// -----------------------------------------------------------------------------------
HostApi::DeviceIterator HostApi::devicesBegin()
{
DeviceIterator tmp;
tmp.ptr_ = &devices_[0]; // begin (first element)
return tmp;
}
HostApi::DeviceIterator HostApi::devicesEnd()
{
DeviceIterator tmp;
tmp.ptr_ = &devices_[deviceCount()]; // end (one past last element)
return tmp;
}
// -----------------------------------------------------------------------------------
Device &HostApi::defaultInputDevice() const
{
return System::instance().deviceByIndex(info_->defaultInputDevice);
}
Device &HostApi::defaultOutputDevice() const
{
return System::instance().deviceByIndex(info_->defaultOutputDevice);
}
// -----------------------------------------------------------------------------------
bool HostApi::operator==(const HostApi &rhs) const
{
return (typeId() == rhs.typeId());
}
bool HostApi::operator!=(const HostApi &rhs) const
{
return !(*this == rhs);
}
// -----------------------------------------------------------------------------------
} // namespace portaudio

View file

@ -0,0 +1,45 @@
#include "portaudiocpp/InterfaceCallbackStream.hxx"
#include "portaudiocpp/StreamParameters.hxx"
#include "portaudiocpp/Exception.hxx"
#include "portaudiocpp/CallbackInterface.hxx"
namespace portaudio
{
// ---------------------------------------------------------------------------------==
InterfaceCallbackStream::InterfaceCallbackStream()
{
}
InterfaceCallbackStream::InterfaceCallbackStream(const StreamParameters &parameters, CallbackInterface &instance)
{
open(parameters, instance);
}
InterfaceCallbackStream::~InterfaceCallbackStream()
{
try
{
close();
}
catch (...)
{
// ignore all errors
}
}
// ---------------------------------------------------------------------------------==
void InterfaceCallbackStream::open(const StreamParameters &parameters, CallbackInterface &instance)
{
PaError err = Pa_OpenStream(&stream_, parameters.inputParameters().paStreamParameters(), parameters.outputParameters().paStreamParameters(),
parameters.sampleRate(), parameters.framesPerBuffer(), parameters.flags(), &impl::callbackInterfaceToPaCallbackAdapter, static_cast<void *>(&instance));
if (err != paNoError)
{
throw PaException(err);
}
}
}

View file

@ -0,0 +1,4 @@
#include "portaudiocpp/MemFunCallbackStream.hxx"
// (... template class ...)

View file

@ -0,0 +1,195 @@
#include "portaudiocpp/Stream.hxx"
#include <cstddef>
#include "portaudiocpp/Exception.hxx"
#include "portaudiocpp/System.hxx"
namespace portaudio
{
// -----------------------------------------------------------------------------------
Stream::Stream() : stream_(NULL)
{
}
Stream::~Stream()
{
// (can't call close here,
// the derived class should atleast call
// close() in it's deconstructor)
}
// -----------------------------------------------------------------------------------
//////
/// Closes the Stream if it's open, else does nothing.
//////
void Stream::close()
{
if (isOpen() && System::exists())
{
PaError err = Pa_CloseStream(stream_);
stream_ = NULL;
if (err != paNoError)
throw PaException(err);
}
}
//////
/// Returns true if the Stream is open.
//////
bool Stream::isOpen() const
{
return (stream_ != NULL);
}
// -----------------------------------------------------------------------------------
void Stream::setStreamFinishedCallback(PaStreamFinishedCallback *callback)
{
PaError err = Pa_SetStreamFinishedCallback(stream_, callback);
if (err != paNoError)
throw PaException(err);
}
// -----------------------------------------------------------------------------------
void Stream::start()
{
PaError err = Pa_StartStream(stream_);
if (err != paNoError)
throw PaException(err);
}
void Stream::stop()
{
PaError err = Pa_StopStream(stream_);
if (err != paNoError)
throw PaException(err);
}
void Stream::abort()
{
PaError err = Pa_AbortStream(stream_);
if (err != paNoError)
throw PaException(err);
}
bool Stream::isStopped() const
{
PaError ret = Pa_IsStreamStopped(stream_);
if (ret < 0)
throw PaException(ret);
return (ret == 1);
}
bool Stream::isActive() const
{
PaError ret = Pa_IsStreamActive(stream_);
if (ret < 0)
throw PaException(ret);
return (ret == 1);
}
// -----------------------------------------------------------------------------------
//////
/// Returns the best known input latency for the Stream. This value may differ from the
/// suggested input latency set in the StreamParameters. Includes all sources of
/// latency known to PortAudio such as internal buffering, and Host API reported latency.
/// Doesn't include any estimates of unknown latency.
//////
PaTime Stream::inputLatency() const
{
const PaStreamInfo *info = Pa_GetStreamInfo(stream_);
if (info == NULL)
{
throw PaException(paInternalError);
return PaTime(0.0);
}
return info->inputLatency;
}
//////
/// Returns the best known output latency for the Stream. This value may differ from the
/// suggested output latency set in the StreamParameters. Includes all sources of
/// latency known to PortAudio such as internal buffering, and Host API reported latency.
/// Doesn't include any estimates of unknown latency.
//////
PaTime Stream::outputLatency() const
{
const PaStreamInfo *info = Pa_GetStreamInfo(stream_);
if (info == NULL)
{
throw PaException(paInternalError);
return PaTime(0.0);
}
return info->outputLatency;
}
//////
/// Returns the sample rate of the Stream. Usually this will be the
/// best known estimate of the used sample rate. For instance when opening a
/// Stream setting 44100.0 Hz in the StreamParameters, the actual sample
/// rate might be something like 44103.2 Hz (due to imperfections in the
/// sound card hardware).
//////
double Stream::sampleRate() const
{
const PaStreamInfo *info = Pa_GetStreamInfo(stream_);
if (info == NULL)
{
throw PaException(paInternalError);
return 0.0;
}
return info->sampleRate;
}
// -----------------------------------------------------------------------------------
PaTime Stream::time() const
{
return Pa_GetStreamTime(stream_);
}
// -----------------------------------------------------------------------------------
//////
/// Accessor (const) for PortAudio PaStream pointer, useful for interfacing with
/// PortAudio add-ons such as PortMixer for instance. Normally accessing this
/// pointer should not be needed as PortAudioCpp aims to provide all of PortAudio's
/// functionality.
//////
const PaStream *Stream::paStream() const
{
return stream_;
}
//////
/// Accessor (non-const) for PortAudio PaStream pointer, useful for interfacing with
/// PortAudio add-ons such as PortMixer for instance. Normally accessing this
/// pointer should not be needed as PortAudioCpp aims to provide all of PortAudio's
/// functionality.
//////
PaStream *Stream::paStream()
{
return stream_;
}
// -----------------------------------------------------------------------------------
} // namespace portaudio

View file

@ -0,0 +1,165 @@
#include "portaudiocpp/StreamParameters.hxx"
#include <cstddef>
#include "portaudiocpp/Device.hxx"
namespace portaudio
{
// -----------------------------------------------------------------------------------
//////
/// Default constructor; does nothing.
//////
StreamParameters::StreamParameters()
{
}
//////
/// Sets up the all parameters needed to open either a half-duplex or full-duplex Stream.
///
/// @param inputParameters The parameters for the input direction of the to-be opened
/// Stream or DirectionSpecificStreamParameters::null() for an output-only Stream.
/// @param outputParameters The parameters for the output direction of the to-be opened
/// Stream or DirectionSpecificStreamParameters::null() for an input-only Stream.
/// @param sampleRate The to-be opened Stream's sample rate in Hz.
/// @param framesPerBuffer The number of frames per buffer for a CallbackStream, or
/// the preferred buffer granularity for a BlockingStream.
/// @param flags The flags for the to-be opened Stream; default paNoFlag.
//////
StreamParameters::StreamParameters(const DirectionSpecificStreamParameters &inputParameters,
const DirectionSpecificStreamParameters &outputParameters, double sampleRate, unsigned long framesPerBuffer,
PaStreamFlags flags) : inputParameters_(inputParameters), outputParameters_(outputParameters),
sampleRate_(sampleRate), framesPerBuffer_(framesPerBuffer), flags_(flags)
{
}
// -----------------------------------------------------------------------------------
//////
/// Sets the requested sample rate. If this sample rate isn't supported by the hardware, the
/// Stream will fail to open. The real-life sample rate used might differ slightly due to
/// imperfections in the sound card hardware; use Stream::sampleRate() to retrieve the
/// best known estimate for this value.
//////
void StreamParameters::setSampleRate(double sampleRate)
{
sampleRate_ = sampleRate;
}
//////
/// Either the number of frames per buffer for a CallbackStream, or
/// the preferred buffer granularity for a BlockingStream. See PortAudio
/// documentation.
//////
void StreamParameters::setFramesPerBuffer(unsigned long framesPerBuffer)
{
framesPerBuffer_ = framesPerBuffer;
}
//////
/// Sets the specified flag or does nothing when the flag is already set. Doesn't
/// `unset' any previously existing flags (use clearFlags() for that).
//////
void StreamParameters::setFlag(PaStreamFlags flag)
{
flags_ |= flag;
}
//////
/// Unsets the specified flag or does nothing if the flag isn't set. Doesn't affect
/// any other flags.
//////
void StreamParameters::unsetFlag(PaStreamFlags flag)
{
flags_ &= ~flag;
}
//////
/// Clears or `unsets' all set flags.
//////
void StreamParameters::clearFlags()
{
flags_ = paNoFlag;
}
// -----------------------------------------------------------------------------------
void StreamParameters::setInputParameters(const DirectionSpecificStreamParameters &parameters)
{
inputParameters_ = parameters;
}
void StreamParameters::setOutputParameters(const DirectionSpecificStreamParameters &parameters)
{
outputParameters_ = parameters;
}
// -----------------------------------------------------------------------------------
bool StreamParameters::isSupported() const
{
return (Pa_IsFormatSupported(inputParameters_.paStreamParameters(),
outputParameters_.paStreamParameters(), sampleRate_) == paFormatIsSupported);
}
// -----------------------------------------------------------------------------------
double StreamParameters::sampleRate() const
{
return sampleRate_;
}
unsigned long StreamParameters::framesPerBuffer() const
{
return framesPerBuffer_;
}
//////
/// Returns all currently set flags as a binary combined
/// integer value (PaStreamFlags). Use isFlagSet() to
/// avoid dealing with the bitmasks.
//////
PaStreamFlags StreamParameters::flags() const
{
return flags_;
}
//////
/// Returns true if the specified flag is currently set
/// or false if it isn't.
//////
bool StreamParameters::isFlagSet(PaStreamFlags flag) const
{
return ((flags_ & flag) != 0);
}
// -----------------------------------------------------------------------------------
DirectionSpecificStreamParameters &StreamParameters::inputParameters()
{
return inputParameters_;
}
const DirectionSpecificStreamParameters &StreamParameters::inputParameters() const
{
return inputParameters_;
}
DirectionSpecificStreamParameters &StreamParameters::outputParameters()
{
return outputParameters_;
}
const DirectionSpecificStreamParameters &StreamParameters::outputParameters() const
{
return outputParameters_;
}
// -----------------------------------------------------------------------------------
} // namespace portaudio

View file

@ -0,0 +1,308 @@
#include "portaudiocpp/System.hxx"
#include <cstddef>
#include <cassert>
#include "portaudiocpp/HostApi.hxx"
#include "portaudiocpp/Device.hxx"
#include "portaudiocpp/Stream.hxx"
#include "portaudiocpp/Exception.hxx"
#include "portaudiocpp/SystemHostApiIterator.hxx"
#include "portaudiocpp/SystemDeviceIterator.hxx"
namespace portaudio
{
// -----------------------------------------------------------------------------------
// Static members:
System *System::instance_ = NULL;
int System::initCount_ = 0;
HostApi **System::hostApis_ = NULL;
Device **System::devices_ = NULL;
Device *System::nullDevice_ = NULL;
// -----------------------------------------------------------------------------------
int System::version()
{
return Pa_GetVersion();
}
const char *System::versionText()
{
return Pa_GetVersionText();
}
void System::initialize()
{
++initCount_;
if (initCount_ == 1)
{
// Create singleton:
assert(instance_ == NULL);
instance_ = new System();
// Initialize the PortAudio system:
{
PaError err = Pa_Initialize();
if (err != paNoError)
throw PaException(err);
}
// Create and populate device array:
{
int numDevices = instance().deviceCount();
devices_ = new Device*[numDevices];
for (int i = 0; i < numDevices; ++i)
devices_[i] = new Device(i);
}
// Create and populate host api array:
{
int numHostApis = instance().hostApiCount();
hostApis_ = new HostApi*[numHostApis];
for (int i = 0; i < numHostApis; ++i)
hostApis_[i] = new HostApi(i);
}
// Create null device:
nullDevice_ = new Device(paNoDevice);
}
}
void System::terminate()
{
PaError err = paNoError;
if (initCount_ == 1)
{
// Destroy null device:
delete nullDevice_;
// Destroy host api array:
{
if (hostApis_ != NULL)
{
int numHostApis = instance().hostApiCount();
for (int i = 0; i < numHostApis; ++i)
delete hostApis_[i];
delete[] hostApis_;
hostApis_ = NULL;
}
}
// Destroy device array:
{
if (devices_ != NULL)
{
int numDevices = instance().deviceCount();
for (int i = 0; i < numDevices; ++i)
delete devices_[i];
delete[] devices_;
devices_ = NULL;
}
}
// Terminate the PortAudio system:
assert(instance_ != NULL);
err = Pa_Terminate();
// Destroy singleton:
delete instance_;
instance_ = NULL;
}
if (initCount_ > 0)
--initCount_;
if (err != paNoError)
throw PaException(err);
}
System &System::instance()
{
assert(exists());
return *instance_;
}
bool System::exists()
{
return (instance_ != NULL);
}
// -----------------------------------------------------------------------------------
System::HostApiIterator System::hostApisBegin()
{
System::HostApiIterator tmp;
tmp.ptr_ = &hostApis_[0]; // begin (first element)
return tmp;
}
System::HostApiIterator System::hostApisEnd()
{
int count = hostApiCount();
System::HostApiIterator tmp;
tmp.ptr_ = &hostApis_[count]; // end (one past last element)
return tmp;
}
HostApi &System::defaultHostApi()
{
PaHostApiIndex defaultHostApi = Pa_GetDefaultHostApi();
if (defaultHostApi < 0)
throw PaException(defaultHostApi);
return *hostApis_[defaultHostApi];
}
HostApi &System::hostApiByTypeId(PaHostApiTypeId type)
{
PaHostApiIndex index = Pa_HostApiTypeIdToHostApiIndex(type);
if (index < 0)
throw PaException(index);
return *hostApis_[index];
}
HostApi &System::hostApiByIndex(PaHostApiIndex index)
{
if (index < 0 || index >= hostApiCount())
throw PaException(paInternalError);
return *hostApis_[index];
}
int System::hostApiCount()
{
PaHostApiIndex count = Pa_GetHostApiCount();
if (count < 0)
throw PaException(count);
return count;
}
// -----------------------------------------------------------------------------------
System::DeviceIterator System::devicesBegin()
{
DeviceIterator tmp;
tmp.ptr_ = &devices_[0];
return tmp;
}
System::DeviceIterator System::devicesEnd()
{
int count = deviceCount();
DeviceIterator tmp;
tmp.ptr_ = &devices_[count];
return tmp;
}
//////
/// Returns the System's default input Device, or the null Device if none
/// was available.
//////
Device &System::defaultInputDevice()
{
PaDeviceIndex index = Pa_GetDefaultInputDevice();
return deviceByIndex(index);
}
//////
/// Returns the System's default output Device, or the null Device if none
/// was available.
//////
Device &System::defaultOutputDevice()
{
PaDeviceIndex index = Pa_GetDefaultOutputDevice();
return deviceByIndex(index);
}
//////
/// Returns the Device for the given index.
/// Will throw a paInternalError equivalent PaException if the given index
/// is out of range.
//////
Device &System::deviceByIndex(PaDeviceIndex index)
{
if (index < -1 || index >= deviceCount())
{
throw PaException(paInternalError);
}
if (index == -1)
return System::instance().nullDevice();
return *devices_[index];
}
int System::deviceCount()
{
PaDeviceIndex count = Pa_GetDeviceCount();
if (count < 0)
throw PaException(count);
return count;
}
Device &System::nullDevice()
{
return *nullDevice_;
}
// -----------------------------------------------------------------------------------
void System::sleep(long msec)
{
Pa_Sleep(msec);
}
int System::sizeOfSample(PaSampleFormat format)
{
PaError err = Pa_GetSampleSize(format);
if (err < 0)
{
throw PaException(err);
return 0;
}
return err;
}
// -----------------------------------------------------------------------------------
System::System()
{
// (left blank intentionally)
}
System::~System()
{
// (left blank intentionally)
}
// -----------------------------------------------------------------------------------
} // namespace portaudio

View file

@ -0,0 +1,60 @@
#include "portaudiocpp/SystemDeviceIterator.hxx"
namespace portaudio
{
// -----------------------------------------------------------------------------------
Device &System::DeviceIterator::operator*() const
{
return **ptr_;
}
Device *System::DeviceIterator::operator->() const
{
return &**this;
}
// -----------------------------------------------------------------------------------
System::DeviceIterator &System::DeviceIterator::operator++()
{
++ptr_;
return *this;
}
System::DeviceIterator System::DeviceIterator::operator++(int)
{
System::DeviceIterator prev = *this;
++*this;
return prev;
}
System::DeviceIterator &System::DeviceIterator::operator--()
{
--ptr_;
return *this;
}
System::DeviceIterator System::DeviceIterator::operator--(int)
{
System::DeviceIterator prev = *this;
--*this;
return prev;
}
// -----------------------------------------------------------------------------------
bool System::DeviceIterator::operator==(const System::DeviceIterator &rhs) const
{
return (ptr_ == rhs.ptr_);
}
bool System::DeviceIterator::operator!=(const System::DeviceIterator &rhs) const
{
return !(*this == rhs);
}
// -----------------------------------------------------------------------------------
} // namespace portaudio

View file

@ -0,0 +1,59 @@
#include "portaudiocpp/SystemHostApiIterator.hxx"
namespace portaudio
{
// -----------------------------------------------------------------------------------
HostApi &System::HostApiIterator::operator*() const
{
return **ptr_;
}
HostApi *System::HostApiIterator::operator->() const
{
return &**this;
}
// -----------------------------------------------------------------------------------
System::HostApiIterator &System::HostApiIterator::operator++()
{
++ptr_;
return *this;
}
System::HostApiIterator System::HostApiIterator::operator++(int)
{
System::HostApiIterator prev = *this;
++*this;
return prev;
}
System::HostApiIterator &System::HostApiIterator::operator--()
{
--ptr_;
return *this;
}
System::HostApiIterator System::HostApiIterator::operator--(int)
{
System::HostApiIterator prev = *this;
--*this;
return prev;
}
// -----------------------------------------------------------------------------------
bool System::HostApiIterator::operator==(const System::HostApiIterator &rhs) const
{
return (ptr_ == rhs.ptr_);
}
bool System::HostApiIterator::operator!=(const System::HostApiIterator &rhs) const
{
return !(*this == rhs);
}
// -----------------------------------------------------------------------------------
} // namespace portaudio

View file

@ -0,0 +1,58 @@
EXPORTS
;
Pa_GetVersion @1
Pa_GetVersionText @2
Pa_GetErrorText @3
Pa_Initialize @4
Pa_Terminate @5
Pa_GetHostApiCount @6
Pa_GetDefaultHostApi @7
Pa_GetHostApiInfo @8
Pa_HostApiTypeIdToHostApiIndex @9
Pa_HostApiDeviceIndexToDeviceIndex @10
Pa_GetLastHostErrorInfo @11
Pa_GetDeviceCount @12
Pa_GetDefaultInputDevice @13
Pa_GetDefaultOutputDevice @14
Pa_GetDeviceInfo @15
Pa_IsFormatSupported @16
Pa_OpenStream @17
Pa_OpenDefaultStream @18
Pa_CloseStream @19
Pa_SetStreamFinishedCallback @20
Pa_StartStream @21
Pa_StopStream @22
Pa_AbortStream @23
Pa_IsStreamStopped @24
Pa_IsStreamActive @25
Pa_GetStreamInfo @26
Pa_GetStreamTime @27
Pa_GetStreamCpuLoad @28
Pa_ReadStream @29
Pa_WriteStream @30
Pa_GetStreamReadAvailable @31
Pa_GetStreamWriteAvailable @32
Pa_GetSampleSize @33
Pa_Sleep @34
;OpenMPT PaAsio_GetAvailableBufferSizes @50
;OpenMPT PaAsio_ShowControlPanel @51
PaUtil_InitializeX86PlainConverters @52
;OpenMPT PaAsio_GetInputChannelName @53
;OpenMPT PaAsio_GetOutputChannelName @54
PaUtil_SetDebugPrintFunction @55
PaWasapi_GetAudioClient @56
;OpenMPT PaWasapi_UpdateDeviceList @57
PaWasapi_GetDeviceCurrentFormat @58
PaWasapi_GetDeviceDefaultFormat @59
PaWasapi_GetDeviceMixFormat @60
PaWasapi_GetDeviceRole @61
PaWasapi_ThreadPriorityBoost @62
PaWasapi_ThreadPriorityRevert @63
PaWasapi_GetFramesPerHostBuffer @64
PaWasapi_GetJackCount @65
PaWasapi_GetJackDescription @66
PaWasapiWinrt_SetDefaultDeviceId @67
PaWasapi_SetStreamStateHandler @68
PaWasapiWinrt_PopulateDeviceList @69
PaWasapi_GetIMMDevice @70

View file

@ -0,0 +1,150 @@
#ifndef PA_ASIO_H
#define PA_ASIO_H
/*
* $Id$
* PortAudio Portable Real-Time Audio Library
* ASIO specific extensions
*
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief ASIO-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/** Retrieve legal native buffer sizes for the specified device, in sample frames.
@param device The global index of the device about which the query is being made.
@param minBufferSizeFrames A pointer to the location which will receive the minimum buffer size value.
@param maxBufferSizeFrames A pointer to the location which will receive the maximum buffer size value.
@param preferredBufferSizeFrames A pointer to the location which will receive the preferred buffer size value.
@param granularity A pointer to the location which will receive the "granularity". This value determines
the step size used to compute the legal values between minBufferSizeFrames and maxBufferSizeFrames.
If granularity is -1 then available buffer size values are powers of two.
@see ASIOGetBufferSize in the ASIO SDK.
@note: this function used to be called PaAsio_GetAvailableLatencyValues. There is a
#define that maps PaAsio_GetAvailableLatencyValues to this function for backwards compatibility.
*/
PaError PaAsio_GetAvailableBufferSizes( PaDeviceIndex device,
long *minBufferSizeFrames, long *maxBufferSizeFrames, long *preferredBufferSizeFrames, long *granularity );
/** Backwards compatibility alias for PaAsio_GetAvailableBufferSizes
@see PaAsio_GetAvailableBufferSizes
*/
#define PaAsio_GetAvailableLatencyValues PaAsio_GetAvailableBufferSizes
/** Display the ASIO control panel for the specified device.
@param device The global index of the device whose control panel is to be displayed.
@param systemSpecific On Windows, the calling application's main window handle,
on Macintosh this value should be zero.
*/
PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific );
/** Retrieve a pointer to a string containing the name of the specified
input channel. The string is valid until Pa_Terminate is called.
The string will be no longer than 32 characters including the null terminator.
*/
PaError PaAsio_GetInputChannelName( PaDeviceIndex device, int channelIndex,
const char** channelName );
/** Retrieve a pointer to a string containing the name of the specified
input channel. The string is valid until Pa_Terminate is called.
The string will be no longer than 32 characters including the null terminator.
*/
PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex,
const char** channelName );
/** Set the sample rate of an open paASIO stream.
@param stream The stream to operate on.
@param sampleRate The new sample rate.
Note that this function may fail if the stream is already running and the
ASIO driver does not support switching the sample rate of a running stream.
Returns paIncompatibleStreamHostApi if stream is not a paASIO stream.
*/
PaError PaAsio_SetStreamSampleRate( PaStream* stream, double sampleRate );
#define paAsioUseChannelSelectors (0x01)
typedef struct PaAsioStreamInfo{
unsigned long size; /**< sizeof(PaAsioStreamInfo) */
PaHostApiTypeId hostApiType; /**< paASIO */
unsigned long version; /**< 1 */
unsigned long flags;
/* Support for opening only specific channels of an ASIO device.
If the paAsioUseChannelSelectors flag is set, channelSelectors is a
pointer to an array of integers specifying the device channels to use.
When used, the length of the channelSelectors array must match the
corresponding channelCount parameter to Pa_OpenStream() otherwise a
crash may result.
The values in the selectors array must specify channels within the
range of supported channels for the device or paInvalidChannelCount will
result.
*/
int *channelSelectors;
}PaAsioStreamInfo;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_ASIO_H */

View file

@ -0,0 +1,77 @@
#ifndef PA_JACK_H
#define PA_JACK_H
/*
* $Id:
* PortAudio Portable Real-Time Audio Library
* JACK-specific extensions
*
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
* @ingroup public_header
* @brief JACK-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Set the JACK client name.
*
* During Pa_Initialize, When PA JACK connects as a client of the JACK server, it requests a certain
* name, which is for instance prepended to port names. By default this name is "PortAudio". The
* JACK server may append a suffix to the client name, in order to avoid clashes among clients that
* try to connect with the same name (e.g., different PA JACK clients).
*
* This function must be called before Pa_Initialize, otherwise it won't have any effect. Note that
* the string is not copied, but instead referenced directly, so it must not be freed for as long as
* PA might need it.
* @sa PaJack_GetClientName
*/
PaError PaJack_SetClientName( const char* name );
/** Get the JACK client name used by PA JACK.
*
* The caller is responsible for freeing the returned pointer.
*/
PaError PaJack_GetClientName(const char** clientName);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,107 @@
#ifndef PA_LINUX_ALSA_H
#define PA_LINUX_ALSA_H
/*
* $Id$
* PortAudio Portable Real-Time Audio Library
* ALSA-specific extensions
*
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
* @ingroup public_header
* @brief ALSA-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct PaAlsaStreamInfo
{
unsigned long size;
PaHostApiTypeId hostApiType;
unsigned long version;
const char *deviceString;
}
PaAlsaStreamInfo;
/** Initialize host API specific structure, call this before setting relevant attributes. */
void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info );
/** Instruct whether to enable real-time priority when starting the audio thread.
*
* If this is turned on by the stream is started, the audio callback thread will be created
* with the FIFO scheduling policy, which is suitable for realtime operation.
**/
void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable );
#if 0
void PaAlsa_EnableWatchdog( PaStream *s, int enable );
#endif
/** Get the ALSA-lib card index of this stream's input device. */
PaError PaAlsa_GetStreamInputCard( PaStream *s, int *card );
/** Get the ALSA-lib card index of this stream's output device. */
PaError PaAlsa_GetStreamOutputCard( PaStream *s, int *card );
/** Set the number of periods (buffer fragments) to configure devices with.
*
* By default the number of periods is 4, this is the lowest number of periods that works well on
* the author's soundcard.
* @param numPeriods The number of periods.
*/
PaError PaAlsa_SetNumPeriods( int numPeriods );
/** Set the maximum number of times to retry opening busy device (sleeping for a
* short interval inbetween).
*/
PaError PaAlsa_SetRetriesBusy( int retries );
/** Set the path and name of ALSA library file if PortAudio is configured to load it dynamically (see
* PA_ALSA_DYNAMIC). This setting will overwrite the default name set by PA_ALSA_PATHNAME define.
* @param pathName Full path with filename. Only filename can be used, but dlopen() will lookup default
* searchable directories (/usr/lib;/usr/local/lib) then.
*/
void PaAlsa_SetLibraryPathName( const char *pathName );
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,191 @@
#ifndef PA_MAC_CORE_H
#define PA_MAC_CORE_H
/*
* PortAudio Portable Real-Time Audio Library
* Macintosh Core Audio specific extensions
* portaudio.h should be included before this file.
*
* Copyright (c) 2005-2006 Bjorn Roche
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
* @ingroup public_header
* @brief CoreAudio-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#include <AudioUnit/AudioUnit.h>
#include <AudioToolbox/AudioToolbox.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* A pointer to a paMacCoreStreamInfo may be passed as
* the hostApiSpecificStreamInfo in the PaStreamParameters struct
* when opening a stream or querying the format. Use NULL, for the
* defaults. Note that for duplex streams, flags for input and output
* should be the same or behaviour is undefined.
*/
typedef struct
{
unsigned long size; /**size of whole structure including this header */
PaHostApiTypeId hostApiType; /**host API for which this data is intended */
unsigned long version; /**structure version */
unsigned long flags; /** flags to modify behaviour */
SInt32 const * channelMap; /** Channel map for HAL channel mapping , if not needed, use NULL;*/
unsigned long channelMapSize; /** Channel map size for HAL channel mapping , if not needed, use 0;*/
} PaMacCoreStreamInfo;
/**
* Functions
*/
/** Use this function to initialize a paMacCoreStreamInfo struct
* using the requested flags. Note that channel mapping is turned
* off after a call to this function.
* @param data The datastructure to initialize
* @param flags The flags to initialize the datastructure with.
*/
void PaMacCore_SetupStreamInfo( PaMacCoreStreamInfo *data, unsigned long flags );
/** call this after pa_SetupMacCoreStreamInfo to use channel mapping as described in notes.txt.
* @param data The stream info structure to assign a channel mapping to
* @param channelMap The channel map array, as described in notes.txt. This array pointer will be used directly (ie the underlying data will not be copied), so the caller should not free the array until after the stream has been opened.
* @param channelMapSize The size of the channel map array.
*/
void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, unsigned long channelMapSize );
/**
* Retrieve the AudioDeviceID of the input device assigned to an open stream
*
* @param s The stream to query.
*
* @return A valid AudioDeviceID, or NULL if an error occurred.
*/
AudioDeviceID PaMacCore_GetStreamInputDevice( PaStream* s );
/**
* Retrieve the AudioDeviceID of the output device assigned to an open stream
*
* @param s The stream to query.
*
* @return A valid AudioDeviceID, or NULL if an error occurred.
*/
AudioDeviceID PaMacCore_GetStreamOutputDevice( PaStream* s );
/**
* Returns a statically allocated string with the device's name
* for the given channel. NULL will be returned on failure.
*
* This function's implementation is not complete!
*
* @param device The PortAudio device index.
* @param channel The channel number who's name is requested.
* @return a statically allocated string with the name of the device.
* Because this string is statically allocated, it must be
* copied if it is to be saved and used by the user after
* another call to this function.
*
*/
const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input );
/** Retrieve the range of legal native buffer sizes for the specified device, in sample frames.
@param device The global index of the PortAudio device about which the query is being made.
@param minBufferSizeFrames A pointer to the location which will receive the minimum buffer size value.
@param maxBufferSizeFrames A pointer to the location which will receive the maximum buffer size value.
@see kAudioDevicePropertyBufferFrameSizeRange in the CoreAudio SDK.
*/
PaError PaMacCore_GetBufferSizeRange( PaDeviceIndex device,
long *minBufferSizeFrames, long *maxBufferSizeFrames );
/**
* Flags
*/
/**
* The following flags alter the behaviour of PA on the mac platform.
* they can be ORed together. These should work both for opening and
* checking a device.
*/
/** Allows PortAudio to change things like the device's frame size,
* which allows for much lower latency, but might disrupt the device
* if other programs are using it, even when you are just Querying
* the device. */
#define paMacCoreChangeDeviceParameters (0x01)
/** In combination with the above flag,
* causes the stream opening to fail, unless the exact sample rates
* are supported by the device. */
#define paMacCoreFailIfConversionRequired (0x02)
/** These flags set the SR conversion quality, if required. The weird ordering
* allows Maximum Quality to be the default.*/
#define paMacCoreConversionQualityMin (0x0100)
#define paMacCoreConversionQualityMedium (0x0200)
#define paMacCoreConversionQualityLow (0x0300)
#define paMacCoreConversionQualityHigh (0x0400)
#define paMacCoreConversionQualityMax (0x0000)
/**
* Here are some "preset" combinations of flags (above) to get to some
* common configurations. THIS IS OVERKILL, but if more flags are added
* it won't be.
*/
/**This is the default setting: do as much sample rate conversion as possible
* and as little mucking with the device as possible. */
#define paMacCorePlayNice (0x00)
/**This setting is tuned for pro audio apps. It allows SR conversion on input
and output, but it tries to set the appropriate SR on the device.*/
#define paMacCorePro (0x01)
/**This is a setting to minimize CPU usage and still play nice.*/
#define paMacCoreMinimizeCPUButPlayNice (0x0100)
/**This is a setting to minimize CPU usage, even if that means interrupting the device. */
#define paMacCoreMinimizeCPU (0x0101)
#ifdef __cplusplus
}
#endif /** __cplusplus */
#endif /** PA_MAC_CORE_H */

View file

@ -0,0 +1,95 @@
#ifndef PA_WIN_DS_H
#define PA_WIN_DS_H
/*
* $Id: $
* PortAudio Portable Real-Time Audio Library
* DirectSound specific extensions
*
* Copyright (c) 1999-2007 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief DirectSound-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#include "pa_win_waveformat.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
#define paWinDirectSoundUseLowLevelLatencyParameters (0x01)
#define paWinDirectSoundUseChannelMask (0x04)
typedef struct PaWinDirectSoundStreamInfo{
unsigned long size; /**< sizeof(PaWinDirectSoundStreamInfo) */
PaHostApiTypeId hostApiType; /**< paDirectSound */
unsigned long version; /**< 2 */
unsigned long flags; /**< enable other features of this struct */
/**
low-level latency setting support
Sets the size of the DirectSound host buffer.
When flags contains the paWinDirectSoundUseLowLevelLatencyParameters
this size will be used instead of interpreting the generic latency
parameters to Pa_OpenStream(). If the flag is not set this value is ignored.
If the stream is a full duplex stream the implementation requires that
the values of framesPerBuffer for input and output match (if both are specified).
*/
unsigned long framesPerBuffer;
/**
support for WAVEFORMATEXTENSIBLE channel masks. If flags contains
paWinDirectSoundUseChannelMask this allows you to specify which speakers
to address in a multichannel stream. Constants for channelMask
are specified in pa_win_waveformat.h
*/
PaWinWaveFormatChannelMask channelMask;
}PaWinDirectSoundStreamInfo;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_WIN_DS_H */

View file

@ -0,0 +1,729 @@
#ifndef PA_WIN_WASAPI_H
#define PA_WIN_WASAPI_H
/*
* $Id: $
* PortAudio Portable Real-Time Audio Library
* WASAPI specific extensions
*
* Copyright (c) 1999-2018 Ross Bencina and Phil Burk
* Copyright (c) 2006-2010 David Viens
* Copyright (c) 2010-2018 Dmitry Kostjuchenko
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief WASAPI-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#include "pa_win_waveformat.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/* Stream setup flags. */
typedef enum PaWasapiFlags
{
/* put WASAPI into exclusive mode */
paWinWasapiExclusive = (1 << 0),
/* allow to skip internal PA processing completely */
paWinWasapiRedirectHostProcessor = (1 << 1),
/* assign custom channel mask */
paWinWasapiUseChannelMask = (1 << 2),
/* select non-Event driven method of data read/write
Note: WASAPI Event driven core is capable of 2ms latency!!!, but Polling
method can only provide 15-20ms latency. */
paWinWasapiPolling = (1 << 3),
/* force custom thread priority setting, must be used if PaWasapiStreamInfo::threadPriority
is set to a custom value */
paWinWasapiThreadPriority = (1 << 4),
/* force explicit sample format and do not allow PA to select suitable working format, API will
fail if provided sample format is not supported by audio hardware in Exclusive mode
or system mixer in Shared mode */
paWinWasapiExplicitSampleFormat = (1 << 5),
/* allow API to insert system-level channel matrix mixer and sample rate converter to allow
playback formats that do not match the current configured system settings.
this is in particular required for streams not matching the system mixer sample rate.
only applies in Shared mode. */
paWinWasapiAutoConvert = (1 << 6)
}
PaWasapiFlags;
#define paWinWasapiExclusive (paWinWasapiExclusive)
#define paWinWasapiRedirectHostProcessor (paWinWasapiRedirectHostProcessor)
#define paWinWasapiUseChannelMask (paWinWasapiUseChannelMask)
#define paWinWasapiPolling (paWinWasapiPolling)
#define paWinWasapiThreadPriority (paWinWasapiThreadPriority)
#define paWinWasapiExplicitSampleFormat (paWinWasapiExplicitSampleFormat)
#define paWinWasapiAutoConvert (paWinWasapiAutoConvert)
/* Stream state.
@note Multiple states can be united into a bitmask.
@see PaWasapiStreamStateCallback, PaWasapi_SetStreamStateHandler
*/
typedef enum PaWasapiStreamState
{
/* state change was caused by the error:
Example:
1) If thread execution stopped due to AUDCLNT_E_RESOURCES_INVALIDATED then state
value will contain paWasapiStreamStateError|paWasapiStreamStateThreadStop.
*/
paWasapiStreamStateError = (1 << 0),
/* processing thread is preparing to start execution */
paWasapiStreamStateThreadPrepare = (1 << 1),
/* processing thread started execution (enters its loop) */
paWasapiStreamStateThreadStart = (1 << 2),
/* processing thread stopped execution */
paWasapiStreamStateThreadStop = (1 << 3)
}
PaWasapiStreamState;
#define paWasapiStreamStateError (paWasapiStreamStateError)
#define paWasapiStreamStateThreadPrepare (paWasapiStreamStateThreadPrepare)
#define paWasapiStreamStateThreadStart (paWasapiStreamStateThreadStart)
#define paWasapiStreamStateThreadStop (paWasapiStreamStateThreadStop)
/* Host processor.
Allows to skip internal PA processing completely. paWinWasapiRedirectHostProcessor flag
must be set to the PaWasapiStreamInfo::flags member in order to have host processor
redirected to this callback.
Use with caution! inputFrames and outputFrames depend solely on final device setup.
To query max values of inputFrames/outputFrames use PaWasapi_GetFramesPerHostBuffer.
*/
typedef void (*PaWasapiHostProcessorCallback) (void *inputBuffer, long inputFrames,
void *outputBuffer, long outputFrames, void *userData);
/* Stream state handler.
@param pStream Pointer to PaStream object.
@param stateFlags State flags, a collection of values from PaWasapiStreamState enum.
@param errorId Error id provided by system API (HRESULT).
@param userData Pointer to user data.
@see PaWasapiStreamState
*/
typedef void (*PaWasapiStreamStateCallback) (PaStream *pStream, unsigned int stateFlags,
unsigned int errorId, void *pUserData);
/* Device role. */
typedef enum PaWasapiDeviceRole
{
eRoleRemoteNetworkDevice = 0,
eRoleSpeakers,
eRoleLineLevel,
eRoleHeadphones,
eRoleMicrophone,
eRoleHeadset,
eRoleHandset,
eRoleUnknownDigitalPassthrough,
eRoleSPDIF,
eRoleHDMI,
eRoleUnknownFormFactor
}
PaWasapiDeviceRole;
/* Jack connection type. */
typedef enum PaWasapiJackConnectionType
{
eJackConnTypeUnknown,
eJackConnType3Point5mm,
eJackConnTypeQuarter,
eJackConnTypeAtapiInternal,
eJackConnTypeRCA,
eJackConnTypeOptical,
eJackConnTypeOtherDigital,
eJackConnTypeOtherAnalog,
eJackConnTypeMultichannelAnalogDIN,
eJackConnTypeXlrProfessional,
eJackConnTypeRJ11Modem,
eJackConnTypeCombination
}
PaWasapiJackConnectionType;
/* Jack geometric location. */
typedef enum PaWasapiJackGeoLocation
{
eJackGeoLocUnk = 0,
eJackGeoLocRear = 0x1, /* matches EPcxGeoLocation::eGeoLocRear */
eJackGeoLocFront,
eJackGeoLocLeft,
eJackGeoLocRight,
eJackGeoLocTop,
eJackGeoLocBottom,
eJackGeoLocRearPanel,
eJackGeoLocRiser,
eJackGeoLocInsideMobileLid,
eJackGeoLocDrivebay,
eJackGeoLocHDMI,
eJackGeoLocOutsideMobileLid,
eJackGeoLocATAPI,
eJackGeoLocReserved5,
eJackGeoLocReserved6,
}
PaWasapiJackGeoLocation;
/* Jack general location. */
typedef enum PaWasapiJackGenLocation
{
eJackGenLocPrimaryBox = 0,
eJackGenLocInternal,
eJackGenLocSeparate,
eJackGenLocOther
}
PaWasapiJackGenLocation;
/* Jack's type of port. */
typedef enum PaWasapiJackPortConnection
{
eJackPortConnJack = 0,
eJackPortConnIntegratedDevice,
eJackPortConnBothIntegratedAndJack,
eJackPortConnUnknown
}
PaWasapiJackPortConnection;
/* Thread priority. */
typedef enum PaWasapiThreadPriority
{
eThreadPriorityNone = 0,
eThreadPriorityAudio, //!< Default for Shared mode.
eThreadPriorityCapture,
eThreadPriorityDistribution,
eThreadPriorityGames,
eThreadPriorityPlayback,
eThreadPriorityProAudio, //!< Default for Exclusive mode.
eThreadPriorityWindowManager
}
PaWasapiThreadPriority;
/* Stream descriptor. */
typedef struct PaWasapiJackDescription
{
unsigned long channelMapping;
unsigned long color; /* derived from macro: #define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) */
PaWasapiJackConnectionType connectionType;
PaWasapiJackGeoLocation geoLocation;
PaWasapiJackGenLocation genLocation;
PaWasapiJackPortConnection portConnection;
unsigned int isConnected;
}
PaWasapiJackDescription;
/** Stream category.
Note:
- values are equal to WASAPI AUDIO_STREAM_CATEGORY enum
- supported since Windows 8.0, noop on earlier versions
- values 1,2 are deprecated on Windows 10 and not included into enumeration
@version Available as of 19.6.0
*/
typedef enum PaWasapiStreamCategory
{
eAudioCategoryOther = 0,
eAudioCategoryCommunications = 3,
eAudioCategoryAlerts = 4,
eAudioCategorySoundEffects = 5,
eAudioCategoryGameEffects = 6,
eAudioCategoryGameMedia = 7,
eAudioCategoryGameChat = 8,
eAudioCategorySpeech = 9,
eAudioCategoryMovie = 10,
eAudioCategoryMedia = 11
}
PaWasapiStreamCategory;
/** Stream option.
Note:
- values are equal to WASAPI AUDCLNT_STREAMOPTIONS enum
- supported since Windows 8.1, noop on earlier versions
@version Available as of 19.6.0
*/
typedef enum PaWasapiStreamOption
{
eStreamOptionNone = 0, //!< default
eStreamOptionRaw = 1, //!< bypass WASAPI Audio Engine DSP effects, supported since Windows 8.1
eStreamOptionMatchFormat = 2 //!< force WASAPI Audio Engine into a stream format, supported since Windows 10
}
PaWasapiStreamOption;
/* Stream descriptor. */
typedef struct PaWasapiStreamInfo
{
unsigned long size; /**< sizeof(PaWasapiStreamInfo) */
PaHostApiTypeId hostApiType; /**< paWASAPI */
unsigned long version; /**< 1 */
unsigned long flags; /**< collection of PaWasapiFlags */
/** Support for WAVEFORMATEXTENSIBLE channel masks. If flags contains
paWinWasapiUseChannelMask this allows you to specify which speakers
to address in a multichannel stream. Constants for channelMask
are specified in pa_win_waveformat.h. Will be used only if
paWinWasapiUseChannelMask flag is specified.
*/
PaWinWaveFormatChannelMask channelMask;
/** Delivers raw data to callback obtained from GetBuffer() methods skipping
internal PortAudio processing inventory completely. userData parameter will
be the same that was passed to Pa_OpenStream method. Will be used only if
paWinWasapiRedirectHostProcessor flag is specified.
*/
PaWasapiHostProcessorCallback hostProcessorOutput;
PaWasapiHostProcessorCallback hostProcessorInput;
/** Specifies thread priority explicitly. Will be used only if paWinWasapiThreadPriority flag
is specified.
Please note, if Input/Output streams are opened simultaneously (Full-Duplex mode)
you shall specify same value for threadPriority or othervise one of the values will be used
to setup thread priority.
*/
PaWasapiThreadPriority threadPriority;
/** Stream category.
@see PaWasapiStreamCategory
@version Available as of 19.6.0
*/
PaWasapiStreamCategory streamCategory;
/** Stream option.
@see PaWasapiStreamOption
@version Available as of 19.6.0
*/
PaWasapiStreamOption streamOption;
}
PaWasapiStreamInfo;
/** Returns pointer to WASAPI's IAudioClient object of the stream.
@param pStream Pointer to PaStream object.
@param pAudioClient Pointer to pointer of IAudioClient.
@param bOutput TRUE (1) for output stream, FALSE (0) for input stream.
@return Error code indicating success or failure.
*/
PaError PaWasapi_GetAudioClient( PaStream *pStream, void **pAudioClient, int bOutput );
/** Update device list.
This function is available if PA_WASAPI_MAX_CONST_DEVICE_COUNT is defined during compile time
with maximum constant WASAPI device count (recommended value - 32).
If PA_WASAPI_MAX_CONST_DEVICE_COUNT is set to 0 (or not defined) during compile time the implementation
will not define PaWasapi_UpdateDeviceList() and thus updating device list can only be possible by calling
Pa_Terminate() and then Pa_Initialize().
@return Error code indicating success or failure.
*/
PaError PaWasapi_UpdateDeviceList();
/** Get current audio format of the device assigned to the opened stream.
Format is represented by PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure.
Use this function to reconfirm format if PA's processor is overridden and
paWinWasapiRedirectHostProcessor flag is specified.
@param pStream Pointer to PaStream object.
@param pFormat Pointer to PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure.
@param formatSize Size of PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure in bytes.
@param bOutput TRUE (1) for output stream, FALSE (0) for input stream.
@return Non-negative value indicating the number of bytes copied into format descriptor
or, a PaErrorCode (which is always negative) if PortAudio is not initialized
or an error is encountered.
*/
int PaWasapi_GetDeviceCurrentFormat( PaStream *pStream, void *pFormat, unsigned int formatSize, int bOutput );
/** Get default audio format for the device in Shared Mode.
Format is represented by PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure and obtained
by getting the device property with a PKEY_AudioEngine_DeviceFormat key.
@param pFormat Pointer to PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure.
@param formatSize Size of PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure in bytes.
@param device Device index.
@return Non-negative value indicating the number of bytes copied into format descriptor
or, a PaErrorCode (which is always negative) if PortAudio is not initialized
or an error is encountered.
*/
int PaWasapi_GetDeviceDefaultFormat( void *pFormat, unsigned int formatSize, PaDeviceIndex device );
/** Get mix audio format for the device in Shared Mode.
Format is represented by PaWinWaveFormat or WAVEFORMATEXTENSIBLE structureand obtained by
IAudioClient::GetMixFormat.
@param pFormat Pointer to PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure.
@param formatSize Size of PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure in bytes.
@param device Device index.
@return Non-negative value indicating the number of bytes copied into format descriptor
or, a PaErrorCode (which is always negative) if PortAudio is not initialized
or an error is encountered.
*/
int PaWasapi_GetDeviceMixFormat( void *pFormat, unsigned int formatSize, PaDeviceIndex device );
/** Get device role (PaWasapiDeviceRole enum).
@param device Device index.
@return Non-negative value indicating device role or, a PaErrorCode (which is always negative)
if PortAudio is not initialized or an error is encountered.
*/
int/*PaWasapiDeviceRole*/ PaWasapi_GetDeviceRole( PaDeviceIndex device );
/** Get device IMMDevice pointer
@param device Device index.
@param pAudioClient Pointer to pointer of IMMDevice.
@return Error code indicating success or failure.
*/
PaError PaWasapi_GetIMMDevice( PaDeviceIndex device, void **pIMMDevice );
/** Boost thread priority of calling thread (MMCSS).
Use it for Blocking Interface only inside the thread which makes calls to Pa_WriteStream/Pa_ReadStream.
@param pTask Handle to pointer to priority task. Must be used with PaWasapi_RevertThreadPriority
method to revert thread priority to initial state.
@param priorityClass Id of thread priority of PaWasapiThreadPriority type. Specifying
eThreadPriorityNone does nothing.
@return Error code indicating success or failure.
@see PaWasapi_RevertThreadPriority
*/
PaError PaWasapi_ThreadPriorityBoost( void **pTask, PaWasapiThreadPriority priorityClass );
/** Boost thread priority of calling thread (MMCSS).
Use it for Blocking Interface only inside the thread which makes calls to Pa_WriteStream/Pa_ReadStream.
@param pTask Task handle obtained by PaWasapi_BoostThreadPriority method.
@return Error code indicating success or failure.
@see PaWasapi_BoostThreadPriority
*/
PaError PaWasapi_ThreadPriorityRevert( void *pTask );
/** Get number of frames per host buffer.
It is max value of frames of WASAPI buffer which can be locked for operations.
Use this method as helper to find out max values of inputFrames/outputFrames
of PaWasapiHostProcessorCallback.
@param pStream Pointer to PaStream object.
@param pInput Pointer to variable to receive number of input frames. Can be NULL.
@param pOutput Pointer to variable to receive number of output frames. Can be NULL.
@return Error code indicating success or failure.
@see PaWasapiHostProcessorCallback
*/
PaError PaWasapi_GetFramesPerHostBuffer( PaStream *pStream, unsigned int *pInput, unsigned int *pOutput );
/** Get number of jacks associated with a WASAPI device.
Use this method to determine if there are any jacks associated with the provided WASAPI device.
Not all audio devices will support this capability. This is valid for both input and output devices.
@note Not available on UWP platform.
@param device Device index.
@param pJackCount Pointer to variable to receive number of jacks.
@return Error code indicating success or failure.
@see PaWasapi_GetJackDescription
*/
PaError PaWasapi_GetJackCount( PaDeviceIndex device, int *pJackCount );
/** Get the jack description associated with a WASAPI device and jack number.
Before this function is called, use PaWasapi_GetJackCount to determine the
number of jacks associated with device. If jcount is greater than zero, then
each jack from 0 to jcount can be queried with this function to get the jack
description.
@note Not available on UWP platform.
@param device Device index.
@param jackIndex Jack index.
@param pJackDescription Pointer to PaWasapiJackDescription.
@return Error code indicating success or failure.
@see PaWasapi_GetJackCount
*/
PaError PaWasapi_GetJackDescription( PaDeviceIndex device, int jackIndex, PaWasapiJackDescription *pJackDescription );
/** Set stream state handler.
@param pStream Pointer to PaStream object.
@param fnStateHandler Pointer to state handling function.
@param pUserData Pointer to user data.
@return Error code indicating success or failure.
*/
PaError PaWasapi_SetStreamStateHandler( PaStream *pStream, PaWasapiStreamStateCallback fnStateHandler, void *pUserData );
/** Set default device Id.
By default implementation will use the DEVINTERFACE_AUDIO_RENDER and
DEVINTERFACE_AUDIO_CAPTURE Ids if device Id is not provided explicitly. These default Ids
will not allow to use Exclusive mode on UWP/WinRT platform and thus you must provide
device Id explicitly via this API before calling the Pa_OpenStream().
Device Ids on UWP platform are obtainable via:
Windows::Media::Devices::MediaDevice::GetDefaultAudioRenderId() or
Windows::Media::Devices::MediaDevice::GetDefaultAudioCaptureId() API.
After the call completes, memory referenced by pointers can be freed, as implementation keeps its own copy.
Call this function before calling Pa_IsFormatSupported() when Exclusive mode is requested.
See an example in the IMPORTANT notes.
@note UWP/WinRT platform only.
@param pId Device Id, pointer to the 16-bit Unicode string (WCHAR). If NULL then device Id
will be reset to the default, e.g. DEVINTERFACE_AUDIO_RENDER or DEVINTERFACE_AUDIO_CAPTURE.
@param bOutput TRUE (1) for output (render), FALSE (0) for input (capture).
@return Error code indicating success or failure. Will return paIncompatibleStreamHostApi if library is not compiled
for UWP/WinRT platform. If Id is longer than PA_WASAPI_DEVICE_ID_LEN characters paBufferTooBig will
be returned.
*/
PaError PaWasapiWinrt_SetDefaultDeviceId( const unsigned short *pId, int bOutput );
/** Populate the device list.
By default the implementation will rely on DEVINTERFACE_AUDIO_RENDER and DEVINTERFACE_AUDIO_CAPTURE as
default devices. If device Id is provided by PaWasapiWinrt_SetDefaultDeviceId() then those
device Ids will be used as default and only devices for the device list.
By populating the device list you can provide an additional available audio devices of the system to PA
which are obtainable by:
Windows::Devices::Enumeration::DeviceInformation::FindAllAsync(selector) where selector is obtainable by
Windows::Media::Devices::MediaDevice::GetAudioRenderSelector() or
Windows::Media::Devices::MediaDevice::GetAudioCaptureSelector() API.
After the call completes, memory referenced by pointers can be freed, as implementation keeps its own copy.
You must call PaWasapi_UpdateDeviceList() to update the internal device list of the implementation after
calling this function.
See an example in the IMPORTANT notes.
@note UWP/WinRT platform only.
@param pId Array of device Ids, pointer to the array of pointers of 16-bit Unicode string (WCHAR). If NULL
and count is also 0 then device Ids will be reset to the default. Required.
@param pName Array of device Names, pointer to the array of pointers of 16-bit Unicode string (WCHAR). Optional.
@param pRole Array of device Roles, see PaWasapiDeviceRole and PaWasapi_GetDeviceRole() for more details. Optional.
@param count Number of devices, the number of array elements (pId, pName, pRole). Maximum count of devices
is limited by PA_WASAPI_DEVICE_MAX_COUNT.
@param bOutput TRUE (1) for output (render), FALSE (0) for input (capture).
@return Error code indicating success or failure. Will return paIncompatibleStreamHostApi if library is not compiled
for UWP/WinRT platform. If Id is longer than PA_WASAPI_DEVICE_ID_LEN characters paBufferTooBig will
be returned. If Name is longer than PA_WASAPI_DEVICE_NAME_LEN characters paBufferTooBig will
be returned.
*/
PaError PaWasapiWinrt_PopulateDeviceList( const unsigned short **pId, const unsigned short **pName,
const PaWasapiDeviceRole *pRole, unsigned int count, int bOutput );
/*
IMPORTANT:
WASAPI is implemented for Callback and Blocking interfaces. It supports Shared and Exclusive
share modes.
Exclusive Mode:
Exclusive mode allows to deliver audio data directly to hardware bypassing
software mixing.
Exclusive mode is specified by 'paWinWasapiExclusive' flag.
Callback Interface:
Provides best audio quality with low latency. Callback interface is implemented in
two versions:
1) Event-Driven:
This is the most powerful WASAPI implementation which provides glitch-free
audio at around 3ms latency in Exclusive mode. Lowest possible latency for this mode is
3 ms for HD Audio class audio chips. For the Shared mode latency can not be
lower than 20 ms.
2) Poll-Driven:
Polling is another 2-nd method to operate with WASAPI. It is less efficient than Event-Driven
and provides latency at around 10-13ms. Polling must be used to overcome a system bug
under Windows Vista x64 when application is WOW64(32-bit) and Event-Driven method simply
times out (event handle is never signalled on buffer completion). Please note, such WOW64 bug
does not exist in Vista x86 or Windows 7.
Polling can be setup by specifying 'paWinWasapiPolling' flag. Our WASAPI implementation detects
WOW64 bug and sets 'paWinWasapiPolling' automatically.
Thread priority:
Normally thread priority is set automatically and does not require modification. Although
if user wants some tweaking thread priority can be modified by setting 'paWinWasapiThreadPriority'
flag and specifying 'PaWasapiStreamInfo::threadPriority' with value from PaWasapiThreadPriority
enum.
Blocking Interface:
Blocking interface is implemented but due to above described Poll-Driven method can not
deliver lowest possible latency. Specifying too low latency in Shared mode will result in
distorted audio although Exclusive mode adds stability.
8.24 format:
If paCustomFormat is specified as sample format then the implementation will understand it
as valid 24-bits inside 32-bit container (e.g. wBitsPerSample = 32, Samples.wValidBitsPerSample = 24).
By using paCustomFormat there will be small optimization when samples are be copied
with Copy_24_To_24 by PA processor instead of conversion from packed 3-byte (24-bit) data
with Int24_To_Int32.
Pa_IsFormatSupported:
To check format with correct Share Mode (Exclusive/Shared) you must supply PaWasapiStreamInfo
with flags paWinWasapiExclusive set through member of PaStreamParameters::hostApiSpecificStreamInfo
structure.
If paWinWasapiExplicitSampleFormat flag is provided then implementation will not try to select
suitable close format and will return an error instead of paFormatIsSupported. By specifying
paWinWasapiExplicitSampleFormat flag it is possible to find out what sample formats are
supported by Exclusive or Shared modes.
Pa_OpenStream:
To set desired Share Mode (Exclusive/Shared) you must supply
PaWasapiStreamInfo with flags paWinWasapiExclusive set through member of
PaStreamParameters::hostApiSpecificStreamInfo structure.
Coding style for parameters and structure members of the public API:
1) bXXX - boolean, [1 (TRUE), 0 (FALSE)]
2) pXXX - pointer
3) fnXXX - pointer to function
4) structure members are never prefixed with a type distinguisher
UWP/WinRT:
This platform has number of limitations which do not allow to enumerate audio devices without
an additional external help. Enumeration is possible though from C++/CX, check the related API
Windows::Devices::Enumeration::DeviceInformation::FindAllAsync().
The main limitation is an absence of the device enumeration from inside the PA's implementation.
This problem can be solved by using the following functions:
PaWasapiWinrt_SetDefaultDeviceId() - to set default input/output device,
PaWasapiWinrt_PopulateDeviceList() - to populate device list with devices.
Here is an example of populating the device list which can also be updated dynamically depending on
whether device was removed from or added to the system:
----------------
std::vector<const UINT16 *> ids, names;
std::vector<PaWasapiDeviceRole> role;
ids.resize(count);
names.resize(count);
role.resize(count);
for (UINT32 i = 0; i < count; ++i)
{
ids[i] = (const UINT16 *)device_ids[i].c_str();
names[i] = (const UINT16 *)device_names[i].c_str();
role[i] = eRoleUnknownFormFactor;
}
PaWasapiWinrt_SetDefaultDeviceId((const UINT16 *)default_device_id.c_str(), !capture);
PaWasapiWinrt_PopulateDeviceList(ids.data(), names.data(), role.data(), count, !capture);
PaWasapi_UpdateDeviceList();
----------------
*/
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_WIN_WASAPI_H */

View file

@ -0,0 +1,199 @@
#ifndef PA_WIN_WAVEFORMAT_H
#define PA_WIN_WAVEFORMAT_H
/*
* PortAudio Portable Real-Time Audio Library
* Windows WAVEFORMAT* data structure utilities
* portaudio.h should be included before this file.
*
* Copyright (c) 2007 Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief Windows specific PortAudio API extension and utilities header file.
*/
#ifdef __cplusplus
extern "C" {
#endif
/*
The following #defines for speaker channel masks are the same
as those in ksmedia.h, except with PAWIN_ prepended, KSAUDIO_ removed
in some cases, and casts to PaWinWaveFormatChannelMask added.
*/
typedef unsigned long PaWinWaveFormatChannelMask;
/* Speaker Positions: */
#define PAWIN_SPEAKER_FRONT_LEFT ((PaWinWaveFormatChannelMask)0x1)
#define PAWIN_SPEAKER_FRONT_RIGHT ((PaWinWaveFormatChannelMask)0x2)
#define PAWIN_SPEAKER_FRONT_CENTER ((PaWinWaveFormatChannelMask)0x4)
#define PAWIN_SPEAKER_LOW_FREQUENCY ((PaWinWaveFormatChannelMask)0x8)
#define PAWIN_SPEAKER_BACK_LEFT ((PaWinWaveFormatChannelMask)0x10)
#define PAWIN_SPEAKER_BACK_RIGHT ((PaWinWaveFormatChannelMask)0x20)
#define PAWIN_SPEAKER_FRONT_LEFT_OF_CENTER ((PaWinWaveFormatChannelMask)0x40)
#define PAWIN_SPEAKER_FRONT_RIGHT_OF_CENTER ((PaWinWaveFormatChannelMask)0x80)
#define PAWIN_SPEAKER_BACK_CENTER ((PaWinWaveFormatChannelMask)0x100)
#define PAWIN_SPEAKER_SIDE_LEFT ((PaWinWaveFormatChannelMask)0x200)
#define PAWIN_SPEAKER_SIDE_RIGHT ((PaWinWaveFormatChannelMask)0x400)
#define PAWIN_SPEAKER_TOP_CENTER ((PaWinWaveFormatChannelMask)0x800)
#define PAWIN_SPEAKER_TOP_FRONT_LEFT ((PaWinWaveFormatChannelMask)0x1000)
#define PAWIN_SPEAKER_TOP_FRONT_CENTER ((PaWinWaveFormatChannelMask)0x2000)
#define PAWIN_SPEAKER_TOP_FRONT_RIGHT ((PaWinWaveFormatChannelMask)0x4000)
#define PAWIN_SPEAKER_TOP_BACK_LEFT ((PaWinWaveFormatChannelMask)0x8000)
#define PAWIN_SPEAKER_TOP_BACK_CENTER ((PaWinWaveFormatChannelMask)0x10000)
#define PAWIN_SPEAKER_TOP_BACK_RIGHT ((PaWinWaveFormatChannelMask)0x20000)
/* Bit mask locations reserved for future use */
#define PAWIN_SPEAKER_RESERVED ((PaWinWaveFormatChannelMask)0x7FFC0000)
/* Used to specify that any possible permutation of speaker configurations */
#define PAWIN_SPEAKER_ALL ((PaWinWaveFormatChannelMask)0x80000000)
/* DirectSound Speaker Config */
#define PAWIN_SPEAKER_DIRECTOUT 0
#define PAWIN_SPEAKER_MONO (PAWIN_SPEAKER_FRONT_CENTER)
#define PAWIN_SPEAKER_STEREO (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT)
#define PAWIN_SPEAKER_QUAD (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT)
#define PAWIN_SPEAKER_SURROUND (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_BACK_CENTER)
#define PAWIN_SPEAKER_5POINT1 (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT)
#define PAWIN_SPEAKER_7POINT1 (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT | \
PAWIN_SPEAKER_FRONT_LEFT_OF_CENTER | PAWIN_SPEAKER_FRONT_RIGHT_OF_CENTER)
#define PAWIN_SPEAKER_5POINT1_SURROUND (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
PAWIN_SPEAKER_SIDE_LEFT | PAWIN_SPEAKER_SIDE_RIGHT)
#define PAWIN_SPEAKER_7POINT1_SURROUND (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT | \
PAWIN_SPEAKER_SIDE_LEFT | PAWIN_SPEAKER_SIDE_RIGHT)
/*
According to the Microsoft documentation:
The following are obsolete 5.1 and 7.1 settings (they lack side speakers). Note this means
that the default 5.1 and 7.1 settings (KSAUDIO_SPEAKER_5POINT1 and KSAUDIO_SPEAKER_7POINT1 are
similarly obsolete but are unchanged for compatibility reasons).
*/
#define PAWIN_SPEAKER_5POINT1_BACK PAWIN_SPEAKER_5POINT1
#define PAWIN_SPEAKER_7POINT1_WIDE PAWIN_SPEAKER_7POINT1
/* DVD Speaker Positions */
#define PAWIN_SPEAKER_GROUND_FRONT_LEFT PAWIN_SPEAKER_FRONT_LEFT
#define PAWIN_SPEAKER_GROUND_FRONT_CENTER PAWIN_SPEAKER_FRONT_CENTER
#define PAWIN_SPEAKER_GROUND_FRONT_RIGHT PAWIN_SPEAKER_FRONT_RIGHT
#define PAWIN_SPEAKER_GROUND_REAR_LEFT PAWIN_SPEAKER_BACK_LEFT
#define PAWIN_SPEAKER_GROUND_REAR_RIGHT PAWIN_SPEAKER_BACK_RIGHT
#define PAWIN_SPEAKER_TOP_MIDDLE PAWIN_SPEAKER_TOP_CENTER
#define PAWIN_SPEAKER_SUPER_WOOFER PAWIN_SPEAKER_LOW_FREQUENCY
/*
PaWinWaveFormat is defined here to provide compatibility with
compilation environments which don't have headers defining
WAVEFORMATEXTENSIBLE (e.g. older versions of MSVC, Borland C++ etc.
The fields for WAVEFORMATEX and WAVEFORMATEXTENSIBLE are declared as an
unsigned char array here to avoid clients who include this file having
a dependency on windows.h and mmsystem.h, and also to to avoid having
to write separate packing pragmas for each compiler.
*/
#define PAWIN_SIZEOF_WAVEFORMATEX 18
#define PAWIN_SIZEOF_WAVEFORMATEXTENSIBLE (PAWIN_SIZEOF_WAVEFORMATEX + 22)
typedef struct{
unsigned char fields[ PAWIN_SIZEOF_WAVEFORMATEXTENSIBLE ];
unsigned long extraLongForAlignment; /* ensure that compiler aligns struct to DWORD */
} PaWinWaveFormat;
/*
WAVEFORMATEXTENSIBLE fields:
union {
WORD wValidBitsPerSample;
WORD wSamplesPerBlock;
WORD wReserved;
} Samples;
DWORD dwChannelMask;
GUID SubFormat;
*/
#define PAWIN_INDEXOF_WVALIDBITSPERSAMPLE (PAWIN_SIZEOF_WAVEFORMATEX+0)
#define PAWIN_INDEXOF_DWCHANNELMASK (PAWIN_SIZEOF_WAVEFORMATEX+2)
#define PAWIN_INDEXOF_SUBFORMAT (PAWIN_SIZEOF_WAVEFORMATEX+6)
/*
Valid values to pass for the waveFormatTag PaWin_InitializeWaveFormatEx and
PaWin_InitializeWaveFormatExtensible functions below. These must match
the standard Windows WAVE_FORMAT_* values.
*/
#define PAWIN_WAVE_FORMAT_PCM (1)
#define PAWIN_WAVE_FORMAT_IEEE_FLOAT (3)
#define PAWIN_WAVE_FORMAT_DOLBY_AC3_SPDIF (0x0092)
#define PAWIN_WAVE_FORMAT_WMA_SPDIF (0x0164)
/*
returns PAWIN_WAVE_FORMAT_PCM or PAWIN_WAVE_FORMAT_IEEE_FLOAT
depending on the sampleFormat parameter.
*/
int PaWin_SampleFormatToLinearWaveFormatTag( PaSampleFormat sampleFormat );
/*
Use the following two functions to initialize the waveformat structure.
*/
void PaWin_InitializeWaveFormatEx( PaWinWaveFormat *waveFormat,
int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate );
void PaWin_InitializeWaveFormatExtensible( PaWinWaveFormat *waveFormat,
int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate,
PaWinWaveFormatChannelMask channelMask );
/* Map a channel count to a speaker channel mask */
PaWinWaveFormatChannelMask PaWin_DefaultChannelMask( int numChannels );
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_WIN_WAVEFORMAT_H */

View file

@ -0,0 +1,137 @@
#ifndef PA_WIN_WDMKS_H
#define PA_WIN_WDMKS_H
/*
* $Id$
* PortAudio Portable Real-Time Audio Library
* WDM/KS specific extensions
*
* Copyright (c) 1999-2007 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief WDM Kernel Streaming-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#include <windows.h>
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/** Flags to indicate valid fields in PaWinWDMKSInfo.
@see PaWinWDMKSInfo
@version Available as of 19.5.0.
*/
typedef enum PaWinWDMKSFlags
{
/** Makes WDMKS use the supplied latency figures instead of relying on the frame size reported
by the WaveCyclic device. Use at own risk!
*/
paWinWDMKSOverrideFramesize = (1 << 0),
/** Makes WDMKS (output stream) use the given channelMask instead of the default.
@version Available as of 19.5.0.
*/
paWinWDMKSUseGivenChannelMask = (1 << 1),
} PaWinWDMKSFlags;
typedef struct PaWinWDMKSInfo{
unsigned long size; /**< sizeof(PaWinWDMKSInfo) */
PaHostApiTypeId hostApiType; /**< paWDMKS */
unsigned long version; /**< 1 */
/** Flags indicate which fields are valid.
@see PaWinWDMKSFlags
@version Available as of 19.5.0.
*/
unsigned long flags;
/** The number of packets to use for WaveCyclic devices, range is [2, 8]. Set to zero for default value of 2. */
unsigned noOfPackets;
/** If paWinWDMKSUseGivenChannelMask bit is set in flags, use this as channelMask instead of default.
@see PaWinWDMKSFlags
@version Available as of 19.5.0.
*/
unsigned channelMask;
} PaWinWDMKSInfo;
typedef enum PaWDMKSType
{
Type_kNotUsed,
Type_kWaveCyclic,
Type_kWaveRT,
Type_kCnt,
} PaWDMKSType;
typedef enum PaWDMKSSubType
{
SubType_kUnknown,
SubType_kNotification,
SubType_kPolled,
SubType_kCnt,
} PaWDMKSSubType;
typedef struct PaWinWDMKSDeviceInfo {
wchar_t filterPath[MAX_PATH]; /**< KS filter path in Unicode! */
wchar_t topologyPath[MAX_PATH]; /**< Topology filter path in Unicode! */
PaWDMKSType streamingType;
GUID deviceProductGuid; /**< The product GUID of the device (if supported) */
} PaWinWDMKSDeviceInfo;
typedef struct PaWDMKSDirectionSpecificStreamInfo
{
PaDeviceIndex device;
unsigned channels; /**< No of channels the device is opened with */
unsigned framesPerHostBuffer; /**< No of frames of the device buffer */
int endpointPinId; /**< Endpoint pin ID (on topology filter if topologyName is not empty) */
int muxNodeId; /**< Only valid for input */
PaWDMKSSubType streamingSubType; /**< Not known until device is opened for streaming */
} PaWDMKSDirectionSpecificStreamInfo;
typedef struct PaWDMKSSpecificStreamInfo {
PaWDMKSDirectionSpecificStreamInfo input;
PaWDMKSDirectionSpecificStreamInfo output;
} PaWDMKSSpecificStreamInfo;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_WIN_DS_H */

View file

@ -0,0 +1,185 @@
#ifndef PA_WIN_WMME_H
#define PA_WIN_WMME_H
/*
* $Id$
* PortAudio Portable Real-Time Audio Library
* MME specific extensions
*
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup public_header
@brief WMME-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#include "pa_win_waveformat.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/* The following are flags which can be set in
PaWinMmeStreamInfo's flags field.
*/
#define paWinMmeUseLowLevelLatencyParameters (0x01)
#define paWinMmeUseMultipleDevices (0x02) /* use mme specific multiple device feature */
#define paWinMmeUseChannelMask (0x04)
/* By default, the mme implementation drops the processing thread's priority
to THREAD_PRIORITY_NORMAL and sleeps the thread if the CPU load exceeds 100%
This flag disables any priority throttling. The processing thread will always
run at THREAD_PRIORITY_TIME_CRITICAL.
*/
#define paWinMmeDontThrottleOverloadedProcessingThread (0x08)
/* Flags for non-PCM spdif passthrough.
*/
#define paWinMmeWaveFormatDolbyAc3Spdif (0x10)
#define paWinMmeWaveFormatWmaSpdif (0x20)
typedef struct PaWinMmeDeviceAndChannelCount{
PaDeviceIndex device;
int channelCount;
}PaWinMmeDeviceAndChannelCount;
typedef struct PaWinMmeStreamInfo{
unsigned long size; /**< sizeof(PaWinMmeStreamInfo) */
PaHostApiTypeId hostApiType; /**< paMME */
unsigned long version; /**< 1 */
unsigned long flags;
/* low-level latency setting support
These settings control the number and size of host buffers in order
to set latency. They will be used instead of the generic parameters
to Pa_OpenStream() if flags contains the PaWinMmeUseLowLevelLatencyParameters
flag.
If PaWinMmeStreamInfo structures with PaWinMmeUseLowLevelLatencyParameters
are supplied for both input and output in a full duplex stream, then the
input and output framesPerBuffer must be the same, or the larger of the
two must be a multiple of the smaller, otherwise a
paIncompatibleHostApiSpecificStreamInfo error will be returned from
Pa_OpenStream().
*/
unsigned long framesPerBuffer;
unsigned long bufferCount; /* formerly numBuffers */
/* multiple devices per direction support
If flags contains the PaWinMmeUseMultipleDevices flag,
this functionality will be used, otherwise the device parameter to
Pa_OpenStream() will be used instead.
If devices are specified here, the corresponding device parameter
to Pa_OpenStream() should be set to paUseHostApiSpecificDeviceSpecification,
otherwise an paInvalidDevice error will result.
The total number of channels across all specified devices
must agree with the corresponding channelCount parameter to
Pa_OpenStream() otherwise a paInvalidChannelCount error will result.
*/
PaWinMmeDeviceAndChannelCount *devices;
unsigned long deviceCount;
/*
support for WAVEFORMATEXTENSIBLE channel masks. If flags contains
paWinMmeUseChannelMask this allows you to specify which speakers
to address in a multichannel stream. Constants for channelMask
are specified in pa_win_waveformat.h
*/
PaWinWaveFormatChannelMask channelMask;
}PaWinMmeStreamInfo;
/** Retrieve the number of wave in handles used by a PortAudio WinMME stream.
Returns zero if the stream is output only.
@return A non-negative value indicating the number of wave in handles
or, a PaErrorCode (which are always negative) if PortAudio is not initialized
or an error is encountered.
@see PaWinMME_GetStreamInputHandle
*/
int PaWinMME_GetStreamInputHandleCount( PaStream* stream );
/** Retrieve a wave in handle used by a PortAudio WinMME stream.
@param stream The stream to query.
@param handleIndex The zero based index of the wave in handle to retrieve. This
should be in the range [0, PaWinMME_GetStreamInputHandleCount(stream)-1].
@return A valid wave in handle, or NULL if an error occurred.
@see PaWinMME_GetStreamInputHandle
*/
HWAVEIN PaWinMME_GetStreamInputHandle( PaStream* stream, int handleIndex );
/** Retrieve the number of wave out handles used by a PortAudio WinMME stream.
Returns zero if the stream is input only.
@return A non-negative value indicating the number of wave out handles
or, a PaErrorCode (which are always negative) if PortAudio is not initialized
or an error is encountered.
@see PaWinMME_GetStreamOutputHandle
*/
int PaWinMME_GetStreamOutputHandleCount( PaStream* stream );
/** Retrieve a wave out handle used by a PortAudio WinMME stream.
@param stream The stream to query.
@param handleIndex The zero based index of the wave out handle to retrieve.
This should be in the range [0, PaWinMME_GetStreamOutputHandleCount(stream)-1].
@return A valid wave out handle, or NULL if an error occurred.
@see PaWinMME_GetStreamOutputHandleCount
*/
HWAVEOUT PaWinMME_GetStreamOutputHandle( PaStream* stream, int handleIndex );
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_WIN_WMME_H */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,242 @@
/*
* $Id$
* Portable Audio I/O Library allocation group implementation
* memory allocation group for tracking allocation groups
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Allocation Group implementation.
*/
#include "pa_allocation.h"
#include "pa_util.h"
/*
Maintain 3 singly linked lists...
linkBlocks: the buffers used to allocate the links
spareLinks: links available for use in the allocations list
allocations: the buffers currently allocated using PaUtil_ContextAllocateMemory()
Link block size is doubled every time new links are allocated.
*/
#define PA_INITIAL_LINK_COUNT_ 16
struct PaUtilAllocationGroupLink
{
struct PaUtilAllocationGroupLink *next;
void *buffer;
};
/*
Allocate a block of links. The first link will have it's buffer member
pointing to the block, and it's next member set to <nextBlock>. The remaining
links will have NULL buffer members, and each link will point to
the next link except the last, which will point to <nextSpare>
*/
static struct PaUtilAllocationGroupLink *AllocateLinks( long count,
struct PaUtilAllocationGroupLink *nextBlock,
struct PaUtilAllocationGroupLink *nextSpare )
{
struct PaUtilAllocationGroupLink *result;
int i;
result = (struct PaUtilAllocationGroupLink *)PaUtil_AllocateMemory(
sizeof(struct PaUtilAllocationGroupLink) * count );
if( result )
{
/* the block link */
result[0].buffer = result;
result[0].next = nextBlock;
/* the spare links */
for( i=1; i<count; ++i )
{
result[i].buffer = 0;
result[i].next = &result[i+1];
}
result[count-1].next = nextSpare;
}
return result;
}
PaUtilAllocationGroup* PaUtil_CreateAllocationGroup( void )
{
PaUtilAllocationGroup* result = 0;
struct PaUtilAllocationGroupLink *links;
links = AllocateLinks( PA_INITIAL_LINK_COUNT_, 0, 0 );
if( links != 0 )
{
result = (PaUtilAllocationGroup*)PaUtil_AllocateMemory( sizeof(PaUtilAllocationGroup) );
if( result )
{
result->linkCount = PA_INITIAL_LINK_COUNT_;
result->linkBlocks = &links[0];
result->spareLinks = &links[1];
result->allocations = 0;
}
else
{
PaUtil_FreeMemory( links );
}
}
return result;
}
void PaUtil_DestroyAllocationGroup( PaUtilAllocationGroup* group )
{
struct PaUtilAllocationGroupLink *current = group->linkBlocks;
struct PaUtilAllocationGroupLink *next;
while( current )
{
next = current->next;
PaUtil_FreeMemory( current->buffer );
current = next;
}
PaUtil_FreeMemory( group );
}
void* PaUtil_GroupAllocateMemory( PaUtilAllocationGroup* group, long size )
{
struct PaUtilAllocationGroupLink *links, *link;
void *result = 0;
/* allocate more links if necessary */
if( !group->spareLinks )
{
/* double the link count on each block allocation */
links = AllocateLinks( group->linkCount, group->linkBlocks, group->spareLinks );
if( links )
{
group->linkCount += group->linkCount;
group->linkBlocks = &links[0];
group->spareLinks = &links[1];
}
}
if( group->spareLinks )
{
result = PaUtil_AllocateMemory( size );
if( result )
{
link = group->spareLinks;
group->spareLinks = link->next;
link->buffer = result;
link->next = group->allocations;
group->allocations = link;
}
}
return result;
}
void PaUtil_GroupFreeMemory( PaUtilAllocationGroup* group, void *buffer )
{
struct PaUtilAllocationGroupLink *current = group->allocations;
struct PaUtilAllocationGroupLink *previous = 0;
if( buffer == 0 )
return;
/* find the right link and remove it */
while( current )
{
if( current->buffer == buffer )
{
if( previous )
{
previous->next = current->next;
}
else
{
group->allocations = current->next;
}
current->buffer = 0;
current->next = group->spareLinks;
group->spareLinks = current;
break;
}
previous = current;
current = current->next;
}
PaUtil_FreeMemory( buffer ); /* free the memory whether we found it in the list or not */
}
void PaUtil_FreeAllAllocations( PaUtilAllocationGroup* group )
{
struct PaUtilAllocationGroupLink *current = group->allocations;
struct PaUtilAllocationGroupLink *previous = 0;
/* free all buffers in the allocations list */
while( current )
{
PaUtil_FreeMemory( current->buffer );
current->buffer = 0;
previous = current;
current = current->next;
}
/* link the former allocations list onto the front of the spareLinks list */
if( previous )
{
previous->next = group->spareLinks;
group->spareLinks = group->allocations;
group->allocations = 0;
}
}

View file

@ -0,0 +1,104 @@
#ifndef PA_ALLOCATION_H
#define PA_ALLOCATION_H
/*
* $Id$
* Portable Audio I/O Library allocation context header
* memory allocation context for tracking allocation groups
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2008 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Allocation Group prototypes. An Allocation Group makes it easy to
allocate multiple blocks of memory and free them all at once.
An allocation group is useful for keeping track of multiple blocks
of memory which are allocated at the same time (such as during initialization)
and need to be deallocated at the same time. The allocation group maintains
a list of allocated blocks, and can free all allocations at once. This
can be useful for cleaning up after a partially initialized object fails.
The allocation group implementation is built on top of the lower
level allocation functions defined in pa_util.h
*/
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
typedef struct
{
long linkCount;
struct PaUtilAllocationGroupLink *linkBlocks;
struct PaUtilAllocationGroupLink *spareLinks;
struct PaUtilAllocationGroupLink *allocations;
}PaUtilAllocationGroup;
/** Create an allocation group.
*/
PaUtilAllocationGroup* PaUtil_CreateAllocationGroup( void );
/** Destroy an allocation group, but not the memory allocated through the group.
*/
void PaUtil_DestroyAllocationGroup( PaUtilAllocationGroup* group );
/** Allocate a block of memory though an allocation group.
*/
void* PaUtil_GroupAllocateMemory( PaUtilAllocationGroup* group, long size );
/** Free a block of memory that was previously allocated though an allocation
group. Calling this function is a relatively time consuming operation.
Under normal circumstances clients should call PaUtil_FreeAllAllocations to
free all allocated blocks simultaneously.
@see PaUtil_FreeAllAllocations
*/
void PaUtil_GroupFreeMemory( PaUtilAllocationGroup* group, void *buffer );
/** Free all blocks of memory which have been allocated through the allocation
group. This function doesn't destroy the group itself.
*/
void PaUtil_FreeAllAllocations( PaUtilAllocationGroup* group );
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_ALLOCATION_H */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,263 @@
#ifndef PA_CONVERTERS_H
#define PA_CONVERTERS_H
/*
* $Id$
* Portable Audio I/O Library sample conversion mechanism
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Phil Burk, Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Conversion functions used to convert buffers of samples from one
format to another.
*/
#include "portaudio.h" /* for PaSampleFormat */
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
struct PaUtilTriangularDitherGenerator;
/** Choose an available sample format which is most appropriate for
representing the requested format. If the requested format is not available
higher quality formats are considered before lower quality formats.
@param availableFormats A variable containing the logical OR of all available
formats.
@param format The desired format.
@return The most appropriate available format for representing the requested
format.
*/
PaSampleFormat PaUtil_SelectClosestAvailableFormat(
PaSampleFormat availableFormats, PaSampleFormat format );
/* high level conversions functions for use by implementations */
/** The generic sample converter prototype. Sample converters convert count
samples from sourceBuffer to destinationBuffer. The actual type of the data
pointed to by these parameters varys for different converter functions.
@param destinationBuffer A pointer to the first sample of the destination.
@param destinationStride An offset between successive destination samples
expressed in samples (not bytes.) It may be negative.
@param sourceBuffer A pointer to the first sample of the source.
@param sourceStride An offset between successive source samples
expressed in samples (not bytes.) It may be negative.
@param count The number of samples to convert.
@param ditherState State information used to calculate dither. Converters
that do not perform dithering will ignore this parameter, in which case
NULL or invalid dither state may be passed.
*/
typedef void PaUtilConverter(
void *destinationBuffer, signed int destinationStride,
void *sourceBuffer, signed int sourceStride,
unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator );
/** Find a sample converter function for the given source and destinations
formats and flags (clip and dither.)
@return
A pointer to a PaUtilConverter which will perform the requested
conversion, or NULL if the given format conversion is not supported.
For conversions where clipping or dithering is not necessary, the
clip and dither flags are ignored and a non-clipping or dithering
version is returned.
If the source and destination formats are the same, a function which
copies data of the appropriate size will be returned.
*/
PaUtilConverter* PaUtil_SelectConverter( PaSampleFormat sourceFormat,
PaSampleFormat destinationFormat, PaStreamFlags flags );
/** The generic buffer zeroer prototype. Buffer zeroers copy count zeros to
destinationBuffer. The actual type of the data pointed to varys for
different zeroer functions.
@param destinationBuffer A pointer to the first sample of the destination.
@param destinationStride An offset between successive destination samples
expressed in samples (not bytes.) It may be negative.
@param count The number of samples to zero.
*/
typedef void PaUtilZeroer(
void *destinationBuffer, signed int destinationStride, unsigned int count );
/** Find a buffer zeroer function for the given destination format.
@return
A pointer to a PaUtilZeroer which will perform the requested
zeroing.
*/
PaUtilZeroer* PaUtil_SelectZeroer( PaSampleFormat destinationFormat );
/*----------------------------------------------------------------------------*/
/* low level functions and data structures which may be used for
substituting conversion functions */
/** The type used to store all sample conversion functions.
@see paConverters;
*/
typedef struct{
PaUtilConverter *Float32_To_Int32;
PaUtilConverter *Float32_To_Int32_Dither;
PaUtilConverter *Float32_To_Int32_Clip;
PaUtilConverter *Float32_To_Int32_DitherClip;
PaUtilConverter *Float32_To_Int24;
PaUtilConverter *Float32_To_Int24_Dither;
PaUtilConverter *Float32_To_Int24_Clip;
PaUtilConverter *Float32_To_Int24_DitherClip;
PaUtilConverter *Float32_To_Int16;
PaUtilConverter *Float32_To_Int16_Dither;
PaUtilConverter *Float32_To_Int16_Clip;
PaUtilConverter *Float32_To_Int16_DitherClip;
PaUtilConverter *Float32_To_Int8;
PaUtilConverter *Float32_To_Int8_Dither;
PaUtilConverter *Float32_To_Int8_Clip;
PaUtilConverter *Float32_To_Int8_DitherClip;
PaUtilConverter *Float32_To_UInt8;
PaUtilConverter *Float32_To_UInt8_Dither;
PaUtilConverter *Float32_To_UInt8_Clip;
PaUtilConverter *Float32_To_UInt8_DitherClip;
PaUtilConverter *Int32_To_Float32;
PaUtilConverter *Int32_To_Int24;
PaUtilConverter *Int32_To_Int24_Dither;
PaUtilConverter *Int32_To_Int16;
PaUtilConverter *Int32_To_Int16_Dither;
PaUtilConverter *Int32_To_Int8;
PaUtilConverter *Int32_To_Int8_Dither;
PaUtilConverter *Int32_To_UInt8;
PaUtilConverter *Int32_To_UInt8_Dither;
PaUtilConverter *Int24_To_Float32;
PaUtilConverter *Int24_To_Int32;
PaUtilConverter *Int24_To_Int16;
PaUtilConverter *Int24_To_Int16_Dither;
PaUtilConverter *Int24_To_Int8;
PaUtilConverter *Int24_To_Int8_Dither;
PaUtilConverter *Int24_To_UInt8;
PaUtilConverter *Int24_To_UInt8_Dither;
PaUtilConverter *Int16_To_Float32;
PaUtilConverter *Int16_To_Int32;
PaUtilConverter *Int16_To_Int24;
PaUtilConverter *Int16_To_Int8;
PaUtilConverter *Int16_To_Int8_Dither;
PaUtilConverter *Int16_To_UInt8;
PaUtilConverter *Int16_To_UInt8_Dither;
PaUtilConverter *Int8_To_Float32;
PaUtilConverter *Int8_To_Int32;
PaUtilConverter *Int8_To_Int24;
PaUtilConverter *Int8_To_Int16;
PaUtilConverter *Int8_To_UInt8;
PaUtilConverter *UInt8_To_Float32;
PaUtilConverter *UInt8_To_Int32;
PaUtilConverter *UInt8_To_Int24;
PaUtilConverter *UInt8_To_Int16;
PaUtilConverter *UInt8_To_Int8;
PaUtilConverter *Copy_8_To_8; /* copy without any conversion */
PaUtilConverter *Copy_16_To_16; /* copy without any conversion */
PaUtilConverter *Copy_24_To_24; /* copy without any conversion */
PaUtilConverter *Copy_32_To_32; /* copy without any conversion */
} PaUtilConverterTable;
/** A table of pointers to all required converter functions.
PaUtil_SelectConverter() uses this table to lookup the appropriate
conversion functions. The fields of this structure are initialized
with default conversion functions. Fields may be NULL, indicating that
no conversion function is available. User code may substitute optimised
conversion functions by assigning different function pointers to
these fields.
@note
If the PA_NO_STANDARD_CONVERTERS preprocessor variable is defined,
PortAudio's standard converters will not be compiled, and all fields
of this structure will be initialized to NULL. In such cases, users
should supply their own conversion functions if the require PortAudio
to open a stream that requires sample conversion.
@see PaUtilConverterTable, PaUtilConverter, PaUtil_SelectConverter
*/
extern PaUtilConverterTable paConverters;
/** The type used to store all buffer zeroing functions.
@see paZeroers;
*/
typedef struct{
PaUtilZeroer *ZeroU8; /* unsigned 8 bit, zero == 128 */
PaUtilZeroer *Zero8;
PaUtilZeroer *Zero16;
PaUtilZeroer *Zero24;
PaUtilZeroer *Zero32;
} PaUtilZeroerTable;
/** A table of pointers to all required zeroer functions.
PaUtil_SelectZeroer() uses this table to lookup the appropriate
conversion functions. The fields of this structure are initialized
with default conversion functions. User code may substitute optimised
conversion functions by assigning different function pointers to
these fields.
@note
If the PA_NO_STANDARD_ZEROERS preprocessor variable is defined,
PortAudio's standard zeroers will not be compiled, and all fields
of this structure will be initialized to NULL. In such cases, users
should supply their own zeroing functions for the sample sizes which
they intend to use.
@see PaUtilZeroerTable, PaUtilZeroer, PaUtil_SelectZeroer
*/
extern PaUtilZeroerTable paZeroers;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_CONVERTERS_H */

View file

@ -0,0 +1,105 @@
/*
* $Id$
* Portable Audio I/O Library CPU Load measurement functions
* Portable CPU load measurement facility.
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 2002 Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Functions to assist in measuring the CPU utilization of a callback
stream. Used to implement the Pa_GetStreamCpuLoad() function.
@todo Dynamically calculate the coefficients used to smooth the CPU Load
Measurements over time to provide a uniform characterisation of CPU Load
independent of rate at which PaUtil_BeginCpuLoadMeasurement /
PaUtil_EndCpuLoadMeasurement are called. see http://www.portaudio.com/trac/ticket/113
*/
#include "pa_cpuload.h"
#include <assert.h>
#include "pa_util.h" /* for PaUtil_GetTime() */
void PaUtil_InitializeCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer, double sampleRate )
{
assert( sampleRate > 0 );
measurer->samplingPeriod = 1. / sampleRate;
measurer->averageLoad = 0.;
}
void PaUtil_ResetCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer )
{
measurer->averageLoad = 0.;
}
void PaUtil_BeginCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer )
{
measurer->measurementStartTime = PaUtil_GetTime();
}
void PaUtil_EndCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer, unsigned long framesProcessed )
{
double measurementEndTime, secondsFor100Percent, measuredLoad;
if( framesProcessed > 0 ){
measurementEndTime = PaUtil_GetTime();
assert( framesProcessed > 0 );
secondsFor100Percent = framesProcessed * measurer->samplingPeriod;
measuredLoad = (measurementEndTime - measurer->measurementStartTime) / secondsFor100Percent;
/* Low pass filter the calculated CPU load to reduce jitter using a simple IIR low pass filter. */
/** FIXME @todo these coefficients shouldn't be hardwired see: http://www.portaudio.com/trac/ticket/113 */
#define LOWPASS_COEFFICIENT_0 (0.9)
#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0)
measurer->averageLoad = (LOWPASS_COEFFICIENT_0 * measurer->averageLoad) +
(LOWPASS_COEFFICIENT_1 * measuredLoad);
}
}
double PaUtil_GetCpuLoad( PaUtilCpuLoadMeasurer* measurer )
{
return measurer->averageLoad;
}

View file

@ -0,0 +1,72 @@
#ifndef PA_CPULOAD_H
#define PA_CPULOAD_H
/*
* $Id$
* Portable Audio I/O Library CPU Load measurement functions
* Portable CPU load measurement facility.
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 2002 Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Functions to assist in measuring the CPU utilization of a callback
stream. Used to implement the Pa_GetStreamCpuLoad() function.
*/
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
typedef struct {
double samplingPeriod;
double measurementStartTime;
double averageLoad;
} PaUtilCpuLoadMeasurer; /**< @todo need better name than measurer */
void PaUtil_InitializeCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer, double sampleRate );
void PaUtil_BeginCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer );
void PaUtil_EndCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer, unsigned long framesProcessed );
void PaUtil_ResetCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer );
double PaUtil_GetCpuLoad( PaUtilCpuLoadMeasurer* measurer );
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_CPULOAD_H */

View file

@ -0,0 +1,123 @@
/*
* $Id: pa_log.c $
* Portable Audio I/O Library Multi-Host API front end
* Validate function parameters and manage multiple host APIs.
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2006 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Implements log function.
PaUtil_SetLogPrintFunction can be user called to replace the provided
DefaultLogPrint function, which writes to stderr.
One can NOT pass var_args across compiler/dll boundaries as it is not
"byte code/abi portable". So the technique used here is to allocate a local
a static array, write in it, then callback the user with a pointer to its
start.
*/
#include <stdio.h>
#include <stdarg.h>
#include "pa_debugprint.h"
// for OutputDebugStringA
#if defined(_MSC_VER) && defined(PA_ENABLE_MSVC_DEBUG_OUTPUT)
#define WIN32_LEAN_AND_MEAN // exclude rare headers
#include "windows.h"
#endif
// User callback
static PaUtilLogCallback userCB = NULL;
// Sets user callback
void PaUtil_SetDebugPrintFunction(PaUtilLogCallback cb)
{
userCB = cb;
}
/*
If your platform doesn't have vsnprintf, you are stuck with a
VERY dangerous alternative, vsprintf (with no n)
*/
#if _MSC_VER
/* Some Windows Mobile SDKs don't define vsnprintf but all define _vsnprintf (hopefully).
According to MSDN "vsnprintf is identical to _vsnprintf". So we use _vsnprintf with MSC.
*/
#define VSNPRINTF _vsnprintf
#else
#define VSNPRINTF vsnprintf
#endif
#define PA_LOG_BUF_SIZE 2048
void PaUtil_DebugPrint( const char *format, ... )
{
// Optional logging into Output console of Visual Studio
#if defined(_MSC_VER) && defined(PA_ENABLE_MSVC_DEBUG_OUTPUT)
{
char buf[PA_LOG_BUF_SIZE];
va_list ap;
va_start(ap, format);
VSNPRINTF(buf, sizeof(buf), format, ap);
buf[sizeof(buf)-1] = 0;
OutputDebugStringA(buf);
va_end(ap);
}
#endif
// Output to User-Callback
if (userCB != NULL)
{
char strdump[PA_LOG_BUF_SIZE];
va_list ap;
va_start(ap, format);
VSNPRINTF(strdump, sizeof(strdump), format, ap);
strdump[sizeof(strdump)-1] = 0;
userCB(strdump);
va_end(ap);
}
else
// Standard output to stderr
{
va_list ap;
va_start(ap, format);
vfprintf(stderr, format, ap);
va_end(ap);
fflush(stderr);
}
}

View file

@ -0,0 +1,149 @@
#ifndef PA_LOG_H
#define PA_LOG_H
/*
* Log file redirector function
* Copyright (c) 1999-2006 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
*/
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
void PaUtil_DebugPrint( const char *format, ... );
/*
The basic format for log messages is described below. If you need to
add any log messages, please follow this format.
Function entry (void function):
"FunctionName called.\n"
Function entry (non void function):
"FunctionName called:\n"
"\tParam1Type param1: param1Value\n"
"\tParam2Type param2: param2Value\n" (etc...)
Function exit (no return value):
"FunctionName returned.\n"
Function exit (simple return value):
"FunctionName returned:\n"
"\tReturnType: returnValue\n"
If the return type is an error code, the error text is displayed in ()
If the return type is not an error code, but has taken a special value
because an error occurred, then the reason for the error is shown in []
If the return type is a struct ptr, the struct is dumped.
See the code below for examples
*/
/** PA_DEBUG() provides a simple debug message printing facility. The macro
passes it's argument to a printf-like function called PaUtil_DebugPrint()
which prints to stderr and always flushes the stream after printing.
Because preprocessor macros cannot directly accept variable length argument
lists, calls to the macro must include an additional set of parenthesis, eg:
PA_DEBUG(("errorno: %d", 1001 ));
*/
#ifdef PA_ENABLE_DEBUG_OUTPUT
#define PA_DEBUG(x) PaUtil_DebugPrint x ;
#else
#define PA_DEBUG(x)
#endif
#ifdef PA_LOG_API_CALLS
#define PA_LOGAPI(x) PaUtil_DebugPrint x
#define PA_LOGAPI_ENTER(functionName) PaUtil_DebugPrint( functionName " called.\n" )
#define PA_LOGAPI_ENTER_PARAMS(functionName) PaUtil_DebugPrint( functionName " called:\n" )
#define PA_LOGAPI_EXIT(functionName) PaUtil_DebugPrint( functionName " returned.\n" )
#define PA_LOGAPI_EXIT_PAERROR( functionName, result ) \
PaUtil_DebugPrint( functionName " returned:\n" ); \
PaUtil_DebugPrint("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) )
#define PA_LOGAPI_EXIT_T( functionName, resultFormatString, result ) \
PaUtil_DebugPrint( functionName " returned:\n" ); \
PaUtil_DebugPrint("\t" resultFormatString "\n", result )
#define PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( functionName, positiveResultFormatString, result ) \
PaUtil_DebugPrint( functionName " returned:\n" ); \
if( result > 0 ) \
PaUtil_DebugPrint("\t" positiveResultFormatString "\n", result ); \
else \
PaUtil_DebugPrint("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) )
#else
#define PA_LOGAPI(x)
#define PA_LOGAPI_ENTER(functionName)
#define PA_LOGAPI_ENTER_PARAMS(functionName)
#define PA_LOGAPI_EXIT(functionName)
#define PA_LOGAPI_EXIT_PAERROR( functionName, result )
#define PA_LOGAPI_EXIT_T( functionName, resultFormatString, result )
#define PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( functionName, positiveResultFormatString, result )
#endif
typedef void (*PaUtilLogCallback ) (const char *log);
/**
Install user provided log function
*/
void PaUtil_SetDebugPrintFunction(PaUtilLogCallback cb);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_LOG_H */

View file

@ -0,0 +1,218 @@
/*
* $Id$
* Portable Audio I/O Library triangular dither generator
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Phil Burk, Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Functions for generating dither noise
*/
#include "pa_types.h"
#include "pa_dither.h"
/* Note that the linear congruential algorithm requires 32 bit integers
* because it uses arithmetic overflow. So use PaUint32 instead of
* unsigned long so it will work on 64 bit systems.
*/
#define PA_DITHER_BITS_ (15)
void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *state )
{
state->previous = 0;
state->randSeed1 = 22222;
state->randSeed2 = 5555555;
}
PaInt32 PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *state )
{
PaInt32 current, highPass;
/* Generate two random numbers. */
state->randSeed1 = (state->randSeed1 * 196314165) + 907633515;
state->randSeed2 = (state->randSeed2 * 196314165) + 907633515;
/* Generate triangular distribution about 0.
* Shift before adding to prevent overflow which would skew the distribution.
* Also shift an extra bit for the high pass filter.
*/
#define DITHER_SHIFT_ ((sizeof(PaInt32)*8 - PA_DITHER_BITS_) + 1)
current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) +
(((PaInt32)state->randSeed2)>>DITHER_SHIFT_);
/* High pass filter to reduce audibility. */
highPass = current - state->previous;
state->previous = current;
return highPass;
}
/* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */
#define PA_FLOAT_DITHER_SCALE_ (1.0f / ((1<<PA_DITHER_BITS_)-1))
static const float const_float_dither_scale_ = PA_FLOAT_DITHER_SCALE_;
float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *state )
{
PaInt32 current, highPass;
/* Generate two random numbers. */
state->randSeed1 = (state->randSeed1 * 196314165) + 907633515;
state->randSeed2 = (state->randSeed2 * 196314165) + 907633515;
/* Generate triangular distribution about 0.
* Shift before adding to prevent overflow which would skew the distribution.
* Also shift an extra bit for the high pass filter.
*/
current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) +
(((PaInt32)state->randSeed2)>>DITHER_SHIFT_);
/* High pass filter to reduce audibility. */
highPass = current - state->previous;
state->previous = current;
return ((float)highPass) * const_float_dither_scale_;
}
/*
The following alternate dither algorithms (from musicdsp.org) could be
considered
*/
/*Noise shaped dither (March 2000)
-------------------
This is a simple implementation of highpass triangular-PDF dither with
2nd-order noise shaping, for use when truncating floating point audio
data to fixed point.
The noise shaping lowers the noise floor by 11dB below 5kHz (@ 44100Hz
sample rate) compared to triangular-PDF dither. The code below assumes
input data is in the range +1 to -1 and doesn't check for overloads!
To save time when generating dither for multiple channels you can do
things like this: r3=(r1 & 0x7F)<<8; instead of calling rand() again.
int r1, r2; //rectangular-PDF random numbers
float s1, s2; //error feedback buffers
float s = 0.5f; //set to 0.0f for no noise shaping
float w = pow(2.0,bits-1); //word length (usually bits=16)
float wi= 1.0f/w;
float d = wi / RAND_MAX; //dither amplitude (2 lsb)
float o = wi * 0.5f; //remove dc offset
float in, tmp;
int out;
//for each sample...
r2=r1; //can make HP-TRI dither by
r1=rand(); //subtracting previous rand()
in += s * (s1 + s1 - s2); //error feedback
tmp = in + o + d * (float)(r1 - r2); //dc offset and dither
out = (int)(w * tmp); //truncate downwards
if(tmp<0.0f) out--; //this is faster than floor()
s2 = s1;
s1 = in - wi * (float)out; //error
--
paul.kellett@maxim.abel.co.uk
http://www.maxim.abel.co.uk
*/
/*
16-to-8-bit first-order dither
Type : First order error feedforward dithering code
References : Posted by Jon Watte
Notes :
This is about as simple a dithering algorithm as you can implement, but it's
likely to sound better than just truncating to N bits.
Note that you might not want to carry forward the full difference for infinity.
It's probably likely that the worst performance hit comes from the saturation
conditionals, which can be avoided with appropriate instructions on many DSPs
and integer SIMD type instructions, or CMOV.
Last, if sound quality is paramount (such as when going from > 16 bits to 16
bits) you probably want to use a higher-order dither function found elsewhere
on this site.
Code :
// This code will down-convert and dither a 16-bit signed short
// mono signal into an 8-bit unsigned char signal, using a first
// order forward-feeding error term dither.
#define uchar unsigned char
void dither_one_channel_16_to_8( short * input, uchar * output, int count, int * memory )
{
int m = *memory;
while( count-- > 0 ) {
int i = *input++;
i += m;
int j = i + 32768 - 128;
uchar o;
if( j < 0 ) {
o = 0;
}
else if( j > 65535 ) {
o = 255;
}
else {
o = (uchar)((j>>8)&0xff);
}
m = ((j-32768+128)-i);
*output++ = o;
}
*memory = m;
}
*/

View file

@ -0,0 +1,106 @@
#ifndef PA_DITHER_H
#define PA_DITHER_H
/*
* $Id$
* Portable Audio I/O Library triangular dither generator
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Phil Burk, Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Functions for generating dither noise
*/
#include "pa_types.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/* Note that the linear congruential algorithm requires 32 bit integers
* because it uses arithmetic overflow. So use PaUint32 instead of
* unsigned long so it will work on 64 bit systems.
*/
/** @brief State needed to generate a dither signal */
typedef struct PaUtilTriangularDitherGenerator{
PaUint32 previous;
PaUint32 randSeed1;
PaUint32 randSeed2;
} PaUtilTriangularDitherGenerator;
/** @brief Initialize dither state */
void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *ditherState );
/**
@brief Calculate 2 LSB dither signal with a triangular distribution.
Ranged for adding to a 1 bit right-shifted 32 bit integer
prior to >>15. eg:
<pre>
signed long in = *
signed long dither = PaUtil_Generate16BitTriangularDither( ditherState );
signed short out = (signed short)(((in>>1) + dither) >> 15);
</pre>
@return
A signed 32-bit integer with a range of +32767 to -32768
*/
PaInt32 PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *ditherState );
/**
@brief Calculate 2 LSB dither signal with a triangular distribution.
Ranged for adding to a pre-scaled float.
<pre>
float in = *
float dither = PaUtil_GenerateFloatTriangularDither( ditherState );
// use smaller scaler to prevent overflow when we add the dither
signed short out = (signed short)(in*(32766.0f) + dither );
</pre>
@return
A float with a range of -2.0 to +1.99999.
*/
float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *ditherState );
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_DITHER_H */

View file

@ -0,0 +1,145 @@
#ifndef PA_ENDIANNESS_H
#define PA_ENDIANNESS_H
/*
* $Id$
* Portable Audio I/O Library current platform endianness macros
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Phil Burk, Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Configure endianness symbols for the target processor.
Arrange for either the PA_LITTLE_ENDIAN or PA_BIG_ENDIAN preprocessor symbols
to be defined. The one that is defined reflects the endianness of the target
platform and may be used to implement conditional compilation of byte-order
dependent code.
If either PA_LITTLE_ENDIAN or PA_BIG_ENDIAN is defined already, then no attempt
is made to override that setting. This may be useful if you have a better way
of determining the platform's endianness. The autoconf mechanism uses this for
example.
A PA_VALIDATE_ENDIANNESS macro is provided to compare the compile time
and runtime endianness and raise an assertion if they don't match.
*/
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/* If this is an apple, we need to do detect endianness this way */
#if defined(__APPLE__)
/* we need to do some endian detection that is sensitive to hardware arch */
#if defined(__LITTLE_ENDIAN__)
#if !defined( PA_LITTLE_ENDIAN )
#define PA_LITTLE_ENDIAN
#endif
#if defined( PA_BIG_ENDIAN )
#undef PA_BIG_ENDIAN
#endif
#else
#if !defined( PA_BIG_ENDIAN )
#define PA_BIG_ENDIAN
#endif
#if defined( PA_LITTLE_ENDIAN )
#undef PA_LITTLE_ENDIAN
#endif
#endif
#else
/* this is not an apple, so first check the existing defines, and, failing that,
detect well-known architectures. */
#if defined(PA_LITTLE_ENDIAN) || defined(PA_BIG_ENDIAN)
/* endianness define has been set externally, such as by autoconf */
#if defined(PA_LITTLE_ENDIAN) && defined(PA_BIG_ENDIAN)
#error both PA_LITTLE_ENDIAN and PA_BIG_ENDIAN have been defined externally to pa_endianness.h - only one endianness at a time please
#endif
#else
/* endianness define has not been set externally */
/* set PA_LITTLE_ENDIAN or PA_BIG_ENDIAN by testing well known platform specific defines */
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) || defined(LITTLE_ENDIAN) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__)
#define PA_LITTLE_ENDIAN /* win32, assume intel byte order */
#else
#define PA_BIG_ENDIAN
#endif
#endif
#if !defined(PA_LITTLE_ENDIAN) && !defined(PA_BIG_ENDIAN)
/*
If the following error is raised, you either need to modify the code above
to automatically determine the endianness from other symbols defined on your
platform, or define either PA_LITTLE_ENDIAN or PA_BIG_ENDIAN externally.
*/
#error pa_endianness.h was unable to automatically determine the endianness of the target platform
#endif
#endif
/* PA_VALIDATE_ENDIANNESS compares the compile time and runtime endianness,
and raises an assertion if they don't match. <assert.h> must be included in
the context in which this macro is used.
*/
#if defined(NDEBUG)
#define PA_VALIDATE_ENDIANNESS
#else
#if defined(PA_LITTLE_ENDIAN)
#define PA_VALIDATE_ENDIANNESS \
{ \
const long nativeOne = 1; \
assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 1 ); \
}
#elif defined(PA_BIG_ENDIAN)
#define PA_VALIDATE_ENDIANNESS \
{ \
const long nativeOne = 1; \
assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 0 ); \
}
#endif
#endif
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_ENDIANNESS_H */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
#define PA_GIT_REVISION 147dd722548358763a8b649b3e4b41dfffbcfbb6

View file

@ -0,0 +1,362 @@
#ifndef PA_HOSTAPI_H
#define PA_HOSTAPI_H
/*
* $Id$
* Portable Audio I/O Library
* host api representation
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2008 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Interfaces and representation structures used by pa_front.c
to manage and communicate with host API implementations.
*/
#include "portaudio.h"
/**
The PA_NO_* host API macros are now deprecated in favor of PA_USE_* macros.
PA_USE_* indicates whether a particular host API will be initialized by PortAudio.
An undefined or 0 value indicates that the host API will not be used. A value of 1
indicates that the host API will be used. PA_USE_* macros should be left undefined
or defined to either 0 or 1.
The code below ensures that PA_USE_* macros are always defined and have value
0 or 1. Undefined symbols are defaulted to 0. Symbols that are neither 0 nor 1
are defaulted to 1.
*/
#ifndef PA_USE_SKELETON
#define PA_USE_SKELETON 0
#elif (PA_USE_SKELETON != 0) && (PA_USE_SKELETON != 1)
#undef PA_USE_SKELETON
#define PA_USE_SKELETON 1
#endif
#if defined(PA_NO_ASIO) || defined(PA_NO_DS) || defined(PA_NO_WMME) || defined(PA_NO_WASAPI) || defined(PA_NO_WDMKS)
#error "Portaudio: PA_NO_<APINAME> is no longer supported, please remove definition and use PA_USE_<APINAME> instead"
#endif
#ifndef PA_USE_ASIO
#define PA_USE_ASIO 0
#elif (PA_USE_ASIO != 0) && (PA_USE_ASIO != 1)
#undef PA_USE_ASIO
#define PA_USE_ASIO 1
#endif
#ifndef PA_USE_DS
#define PA_USE_DS 0
#elif (PA_USE_DS != 0) && (PA_USE_DS != 1)
#undef PA_USE_DS
#define PA_USE_DS 1
#endif
#ifndef PA_USE_WMME
#define PA_USE_WMME 0
#elif (PA_USE_WMME != 0) && (PA_USE_WMME != 1)
#undef PA_USE_WMME
#define PA_USE_WMME 1
#endif
#ifndef PA_USE_WASAPI
#define PA_USE_WASAPI 0
#elif (PA_USE_WASAPI != 0) && (PA_USE_WASAPI != 1)
#undef PA_USE_WASAPI
#define PA_USE_WASAPI 1
#endif
#ifndef PA_USE_WDMKS
#define PA_USE_WDMKS 0
#elif (PA_USE_WDMKS != 0) && (PA_USE_WDMKS != 1)
#undef PA_USE_WDMKS
#define PA_USE_WDMKS 1
#endif
/* Set default values for Unix based APIs. */
#if defined(PA_NO_OSS) || defined(PA_NO_ALSA) || defined(PA_NO_JACK) || defined(PA_NO_COREAUDIO) || defined(PA_NO_SGI) || defined(PA_NO_ASIHPI)
#error "Portaudio: PA_NO_<APINAME> is no longer supported, please remove definition and use PA_USE_<APINAME> instead"
#endif
#ifndef PA_USE_OSS
#define PA_USE_OSS 0
#elif (PA_USE_OSS != 0) && (PA_USE_OSS != 1)
#undef PA_USE_OSS
#define PA_USE_OSS 1
#endif
#ifndef PA_USE_ALSA
#define PA_USE_ALSA 0
#elif (PA_USE_ALSA != 0) && (PA_USE_ALSA != 1)
#undef PA_USE_ALSA
#define PA_USE_ALSA 1
#endif
#ifndef PA_USE_JACK
#define PA_USE_JACK 0
#elif (PA_USE_JACK != 0) && (PA_USE_JACK != 1)
#undef PA_USE_JACK
#define PA_USE_JACK 1
#endif
#ifndef PA_USE_SGI
#define PA_USE_SGI 0
#elif (PA_USE_SGI != 0) && (PA_USE_SGI != 1)
#undef PA_USE_SGI
#define PA_USE_SGI 1
#endif
#ifndef PA_USE_COREAUDIO
#define PA_USE_COREAUDIO 0
#elif (PA_USE_COREAUDIO != 0) && (PA_USE_COREAUDIO != 1)
#undef PA_USE_COREAUDIO
#define PA_USE_COREAUDIO 1
#endif
#ifndef PA_USE_ASIHPI
#define PA_USE_ASIHPI 0
#elif (PA_USE_ASIHPI != 0) && (PA_USE_ASIHPI != 1)
#undef PA_USE_ASIHPI
#define PA_USE_ASIHPI 1
#endif
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/** **FOR THE USE OF pa_front.c ONLY**
Do NOT use fields in this structure, they my change at any time.
Use functions defined in pa_util.h if you think you need functionality
which can be derived from here.
*/
typedef struct PaUtilPrivatePaFrontHostApiInfo {
unsigned long baseDeviceIndex;
}PaUtilPrivatePaFrontHostApiInfo;
/** The common header for all data structures whose pointers are passed through
the hostApiSpecificStreamInfo field of the PaStreamParameters structure.
Note that in order to keep the public PortAudio interface clean, this structure
is not used explicitly when declaring hostApiSpecificStreamInfo data structures.
However, some code in pa_front depends on the first 3 members being equivalent
with this structure.
@see PaStreamParameters
*/
typedef struct PaUtilHostApiSpecificStreamInfoHeader
{
unsigned long size; /**< size of whole structure including this header */
PaHostApiTypeId hostApiType; /**< host API for which this data is intended */
unsigned long version; /**< structure version */
} PaUtilHostApiSpecificStreamInfoHeader;
/** A structure representing the interface to a host API. Contains both
concrete data and pointers to functions which implement the interface.
*/
typedef struct PaUtilHostApiRepresentation {
PaUtilPrivatePaFrontHostApiInfo privatePaFrontInfo;
/** The host api implementation should populate the info field. In the
case of info.defaultInputDevice and info.defaultOutputDevice the
values stored should be 0 based indices within the host api's own
device index range (0 to deviceCount). These values will be converted
to global device indices by pa_front after PaUtilHostApiInitializer()
returns.
*/
PaHostApiInfo info;
PaDeviceInfo** deviceInfos;
/**
(*Terminate)() is guaranteed to be called with a valid <hostApi>
parameter, which was previously returned from the same implementation's
initializer.
*/
void (*Terminate)( struct PaUtilHostApiRepresentation *hostApi );
/**
The inputParameters and outputParameters pointers should not be saved
as they will not remain valid after OpenStream is called.
The following guarantees are made about parameters to (*OpenStream)():
[NOTE: the following list up to *END PA FRONT VALIDATIONS* should be
kept in sync with the one for ValidateOpenStreamParameters and
Pa_OpenStream in pa_front.c]
PaHostApiRepresentation *hostApi
- is valid for this implementation
PaStream** stream
- is non-null
- at least one of inputParameters & outputParmeters is valid (not NULL)
- if inputParameters & outputParmeters are both valid, that
inputParameters->device & outputParmeters->device both use the same host api
PaDeviceIndex inputParameters->device
- is within range (0 to Pa_CountDevices-1) Or:
- is paUseHostApiSpecificDeviceSpecification and
inputParameters->hostApiSpecificStreamInfo is non-NULL and refers
to a valid host api
int inputParameters->numChannels
- if inputParameters->device is not paUseHostApiSpecificDeviceSpecification, numInputChannels is > 0
- upper bound is NOT validated against device capabilities
PaSampleFormat inputParameters->sampleFormat
- is one of the sample formats defined in portaudio.h
void *inputParameters->hostApiSpecificStreamInfo
- if supplied its hostApi field matches the input device's host Api
PaDeviceIndex outputParmeters->device
- is within range (0 to Pa_CountDevices-1)
int outputParmeters->numChannels
- if inputDevice is valid, numInputChannels is > 0
- upper bound is NOT validated against device capabilities
PaSampleFormat outputParmeters->sampleFormat
- is one of the sample formats defined in portaudio.h
void *outputParmeters->hostApiSpecificStreamInfo
- if supplied its hostApi field matches the output device's host Api
double sampleRate
- is not an 'absurd' rate (less than 1000. or greater than 384000.)
- sampleRate is NOT validated against device capabilities
PaStreamFlags streamFlags
- unused platform neutral flags are zero
- paNeverDropInput is only used for full-duplex callback streams
with variable buffer size (paFramesPerBufferUnspecified)
[*END PA FRONT VALIDATIONS*]
The following validations MUST be performed by (*OpenStream)():
- check that input device can support numInputChannels
- check that input device can support inputSampleFormat, or that
we have the capability to convert from outputSampleFormat to
a native format
- if inputStreamInfo is supplied, validate its contents,
or return an error if no inputStreamInfo is expected
- check that output device can support numOutputChannels
- check that output device can support outputSampleFormat, or that
we have the capability to convert from outputSampleFormat to
a native format
- if outputStreamInfo is supplied, validate its contents,
or return an error if no outputStreamInfo is expected
- if a full duplex stream is requested, check that the combination
of input and output parameters is supported
- check that the device supports sampleRate
- alter sampleRate to a close allowable rate if necessary
- validate inputLatency and outputLatency
- validate any platform specific flags, if flags are supplied they
must be valid.
*/
PaError (*OpenStream)( struct PaUtilHostApiRepresentation *hostApi,
PaStream** stream,
const PaStreamParameters *inputParameters,
const PaStreamParameters *outputParameters,
double sampleRate,
unsigned long framesPerCallback,
PaStreamFlags streamFlags,
PaStreamCallback *streamCallback,
void *userData );
PaError (*IsFormatSupported)( struct PaUtilHostApiRepresentation *hostApi,
const PaStreamParameters *inputParameters,
const PaStreamParameters *outputParameters,
double sampleRate );
} PaUtilHostApiRepresentation;
/** Prototype for the initialization function which must be implemented by every
host API.
This function should only return an error other than paNoError if it encounters
an unexpected and fatal error (memory allocation error for example). In general,
there may be conditions under which it returns a NULL interface pointer and also
returns paNoError. For example, if the ASIO implementation detects that ASIO is
not installed, it should return a NULL interface, and paNoError.
@see paHostApiInitializers
*/
typedef PaError PaUtilHostApiInitializer( PaUtilHostApiRepresentation**, PaHostApiIndex );
/** paHostApiInitializers is a NULL-terminated array of host API initialization
functions. These functions are called by pa_front.c to initialize the host APIs
when the client calls Pa_Initialize().
The initialization functions are invoked in order.
The first successfully initialized host API that has a default input *or* output
device is used as the default PortAudio host API. This is based on the logic that
there is only one default host API, and it must contain the default input and output
devices (if defined).
There is a platform specific file that defines paHostApiInitializers for that
platform, pa_win/pa_win_hostapis.c contains the Win32 definitions for example.
*/
extern PaUtilHostApiInitializer *paHostApiInitializers[];
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_HOSTAPI_H */

View file

@ -0,0 +1,128 @@
/*
* $Id: pa_memorybarrier.h 1240 2007-07-17 13:05:07Z bjornroche $
* Portable Audio I/O Library
* Memory barrier utilities
*
* Author: Bjorn Roche, XO Audio, LLC
*
* This program uses the PortAudio Portable Audio Library.
* For more information see: http://www.portaudio.com
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/**
@file pa_memorybarrier.h
@ingroup common_src
*/
/****************
* Some memory barrier primitives based on the system.
* right now only OS X, FreeBSD, and Linux are supported. In addition to providing
* memory barriers, these functions should ensure that data cached in registers
* is written out to cache where it can be snooped by other CPUs. (ie, the volatile
* keyword should not be required)
*
* the primitives that must be defined are:
*
* PaUtil_FullMemoryBarrier()
* PaUtil_ReadMemoryBarrier()
* PaUtil_WriteMemoryBarrier()
*
****************/
#if defined(__APPLE__)
# include <libkern/OSAtomic.h>
/* Here are the memory barrier functions. Mac OS X only provides
full memory barriers, so the three types of barriers are the same,
however, these barriers are superior to compiler-based ones. */
# define PaUtil_FullMemoryBarrier() OSMemoryBarrier()
# define PaUtil_ReadMemoryBarrier() OSMemoryBarrier()
# define PaUtil_WriteMemoryBarrier() OSMemoryBarrier()
#elif defined(__GNUC__)
/* GCC >= 4.1 has built-in intrinsics. We'll use those */
# if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
# define PaUtil_FullMemoryBarrier() __sync_synchronize()
# define PaUtil_ReadMemoryBarrier() __sync_synchronize()
# define PaUtil_WriteMemoryBarrier() __sync_synchronize()
/* as a fallback, GCC understands volatile asm and "memory" to mean it
* should not reorder memory read/writes */
/* Note that it is not clear that any compiler actually defines __PPC__,
* it can probably removed safely. */
# elif defined( __ppc__ ) || defined( __powerpc__) || defined( __PPC__ )
# define PaUtil_FullMemoryBarrier() asm volatile("sync":::"memory")
# define PaUtil_ReadMemoryBarrier() asm volatile("sync":::"memory")
# define PaUtil_WriteMemoryBarrier() asm volatile("sync":::"memory")
# elif defined( __i386__ ) || defined( __i486__ ) || defined( __i586__ ) || \
defined( __i686__ ) || defined( __x86_64__ )
# define PaUtil_FullMemoryBarrier() asm volatile("mfence":::"memory")
# define PaUtil_ReadMemoryBarrier() asm volatile("lfence":::"memory")
# define PaUtil_WriteMemoryBarrier() asm volatile("sfence":::"memory")
# else
# ifdef ALLOW_SMP_DANGERS
# warning Memory barriers not defined on this system or system unknown
# warning For SMP safety, you should fix this.
# define PaUtil_FullMemoryBarrier()
# define PaUtil_ReadMemoryBarrier()
# define PaUtil_WriteMemoryBarrier()
# else
# error Memory barriers are not defined on this system. You can still compile by defining ALLOW_SMP_DANGERS, but SMP safety will not be guaranteed.
# endif
# endif
#elif (_MSC_VER >= 1400) && !defined(_WIN32_WCE)
# include <intrin.h>
# pragma intrinsic(_ReadWriteBarrier)
# pragma intrinsic(_ReadBarrier)
# pragma intrinsic(_WriteBarrier)
/* note that MSVC intrinsics _ReadWriteBarrier(), _ReadBarrier(), _WriteBarrier() are just compiler barriers *not* memory barriers */
# define PaUtil_FullMemoryBarrier() _ReadWriteBarrier()
# define PaUtil_ReadMemoryBarrier() _ReadBarrier()
# define PaUtil_WriteMemoryBarrier() _WriteBarrier()
#elif defined(_WIN32_WCE)
# define PaUtil_FullMemoryBarrier()
# define PaUtil_ReadMemoryBarrier()
# define PaUtil_WriteMemoryBarrier()
#elif defined(_MSC_VER) || defined(__BORLANDC__)
# define PaUtil_FullMemoryBarrier() _asm { lock add [esp], 0 }
# define PaUtil_ReadMemoryBarrier() _asm { lock add [esp], 0 }
# define PaUtil_WriteMemoryBarrier() _asm { lock add [esp], 0 }
#else
# ifdef ALLOW_SMP_DANGERS
# warning Memory barriers not defined on this system or system unknown
# warning For SMP safety, you should fix this.
# define PaUtil_FullMemoryBarrier()
# define PaUtil_ReadMemoryBarrier()
# define PaUtil_WriteMemoryBarrier()
# else
# error Memory barriers are not defined on this system. You can still compile by defining ALLOW_SMP_DANGERS, but SMP safety will not be guaranteed.
# endif
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,754 @@
#ifndef PA_PROCESS_H
#define PA_PROCESS_H
/*
* $Id$
* Portable Audio I/O Library callback buffer processing adapters
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Phil Burk, Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Buffer Processor prototypes. A Buffer Processor performs buffer length
adaption, coordinates sample format conversion, and interleaves/deinterleaves
channels.
<h3>Overview</h3>
The "Buffer Processor" (PaUtilBufferProcessor) manages conversion of audio
data from host buffers to user buffers and back again. Where required, the
buffer processor takes care of converting between host and user sample formats,
interleaving and deinterleaving multichannel buffers, and adapting between host
and user buffers with different lengths. The buffer processor may be used with
full and half duplex streams, for both callback streams and blocking read/write
streams.
One of the important capabilities provided by the buffer processor is
the ability to adapt between user and host buffer sizes of different lengths
with minimum latency. Although this task is relatively easy to perform when
the host buffer size is an integer multiple of the user buffer size, the
problem is more complicated when this is not the case - especially for
full-duplex callback streams. Where necessary the adaption is implemented by
internally buffering some input and/or output data. The buffer adation
algorithm used by the buffer processor was originally implemented by
Stephan Letz for the ASIO version of PortAudio, and is described in his
Callback_adaption_.pdf which is included in the distribution.
The buffer processor performs sample conversion using the functions provided
by pa_converters.c.
The following sections provide an overview of how to use the buffer processor.
Interested readers are advised to consult the host API implementations for
examples of buffer processor usage.
<h4>Initialization, resetting and termination</h4>
When a stream is opened, the buffer processor should be initialized using
PaUtil_InitializeBufferProcessor. This function initializes internal state
and allocates temporary buffers as necessary according to the supplied
configuration parameters. Some of the parameters correspond to those requested
by the user in their call to Pa_OpenStream(), others reflect the requirements
of the host API implementation - they indicate host buffer sizes, formats,
and the type of buffering which the Host API uses. The buffer processor should
be initialized for callback streams and blocking read/write streams.
Call PaUtil_ResetBufferProcessor to clear any sample data which is present
in the buffer processor before starting to use it (for example when
Pa_StartStream is called).
When the buffer processor is no longer used call
PaUtil_TerminateBufferProcessor.
<h4>Using the buffer processor for a callback stream</h4>
The buffer processor's role in a callback stream is to take host input buffers
process them with the stream callback, and fill host output buffers. For a
full duplex stream, the buffer processor handles input and output simultaneously
due to the requirements of the minimum-latency buffer adation algorithm.
When a host buffer becomes available, the implementation should call
the buffer processor to process the buffer. The buffer processor calls the
stream callback to consume and/or produce audio data as necessary. The buffer
processor will convert sample formats, interleave/deinterleave channels,
and slice or chunk the data to the appropriate buffer lengths according to
the requirements of the stream callback and the host API.
To process a host buffer (or a pair of host buffers for a full-duplex stream)
use the following calling sequence:
-# Call PaUtil_BeginBufferProcessing
-# For a stream which takes input:
- Call PaUtil_SetInputFrameCount with the number of frames in the host input
buffer.
- Call one of the following functions one or more times to tell the
buffer processor about the host input buffer(s): PaUtil_SetInputChannel,
PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel.
Which function you call will depend on whether the host buffer(s) are
interleaved or not.
- If the available host data is split across two buffers (for example a
data range at the end of a circular buffer and another range at the
beginning of the circular buffer), also call
PaUtil_Set2ndInputFrameCount, PaUtil_Set2ndInputChannel,
PaUtil_Set2ndInterleavedInputChannels,
PaUtil_Set2ndNonInterleavedInputChannel as necessary to tell the buffer
processor about the second buffer.
-# For a stream which generates output:
- Call PaUtil_SetOutputFrameCount with the number of frames in the host
output buffer.
- Call one of the following functions one or more times to tell the
buffer processor about the host output buffer(s): PaUtil_SetOutputChannel,
PaUtil_SetInterleavedOutputChannels, PaUtil_SetNonInterleavedOutputChannel.
Which function you call will depend on whether the host buffer(s) are
interleaved or not.
- If the available host output buffer space is split across two buffers
(for example a data range at the end of a circular buffer and another
range at the beginning of the circular buffer), call
PaUtil_Set2ndOutputFrameCount, PaUtil_Set2ndOutputChannel,
PaUtil_Set2ndInterleavedOutputChannels,
PaUtil_Set2ndNonInterleavedOutputChannel as necessary to tell the buffer
processor about the second buffer.
-# Call PaUtil_EndBufferProcessing, this function performs the actual data
conversion and processing.
<h4>Using the buffer processor for a blocking read/write stream</h4>
Blocking read/write streams use the buffer processor to convert and copy user
output data to a host buffer, and to convert and copy host input data to
the user's buffer. The buffer processor does not perform any buffer adaption.
When using the buffer processor in a blocking read/write stream the input and
output conversion are performed separately by the PaUtil_CopyInput and
PaUtil_CopyOutput functions.
To copy data from a host input buffer to the buffer(s) which the user supplies
to Pa_ReadStream, use the following calling sequence.
- Repeat the following three steps until the user buffer(s) have been filled
with samples from the host input buffers:
-# Call PaUtil_SetInputFrameCount with the number of frames in the host
input buffer.
-# Call one of the following functions one or more times to tell the
buffer processor about the host input buffer(s): PaUtil_SetInputChannel,
PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel.
Which function you call will depend on whether the host buffer(s) are
interleaved or not.
-# Call PaUtil_CopyInput with the user buffer pointer (or a copy of the
array of buffer pointers for a non-interleaved stream) passed to
Pa_ReadStream, along with the number of frames in the user buffer(s).
Be careful to pass a <i>copy</i> of the user buffer pointers to
PaUtil_CopyInput because PaUtil_CopyInput advances the pointers to
the start of the next region to copy.
- PaUtil_CopyInput will not copy more data than is available in the
host buffer(s), so the above steps need to be repeated until the user
buffer(s) are full.
To copy data to the host output buffer from the user buffers(s) supplied
to Pa_WriteStream use the following calling sequence.
- Repeat the following three steps until all frames from the user buffer(s)
have been copied to the host API:
-# Call PaUtil_SetOutputFrameCount with the number of frames in the host
output buffer.
-# Call one of the following functions one or more times to tell the
buffer processor about the host output buffer(s): PaUtil_SetOutputChannel,
PaUtil_SetInterleavedOutputChannels, PaUtil_SetNonInterleavedOutputChannel.
Which function you call will depend on whether the host buffer(s) are
interleaved or not.
-# Call PaUtil_CopyOutput with the user buffer pointer (or a copy of the
array of buffer pointers for a non-interleaved stream) passed to
Pa_WriteStream, along with the number of frames in the user buffer(s).
Be careful to pass a <i>copy</i> of the user buffer pointers to
PaUtil_CopyOutput because PaUtil_CopyOutput advances the pointers to
the start of the next region to copy.
- PaUtil_CopyOutput will not copy more data than fits in the host buffer(s),
so the above steps need to be repeated until all user data is copied.
*/
#include "portaudio.h"
#include "pa_converters.h"
#include "pa_dither.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/** @brief Mode flag passed to PaUtil_InitializeBufferProcessor indicating the type
of buffering that the host API uses.
The mode used depends on whether the host API or the implementation manages
the buffers, and how these buffers are used (scatter gather, circular buffer).
*/
typedef enum {
/** The host buffer size is a fixed known size. */
paUtilFixedHostBufferSize,
/** The host buffer size may vary, but has a known maximum size. */
paUtilBoundedHostBufferSize,
/** Nothing is known about the host buffer size. */
paUtilUnknownHostBufferSize,
/** The host buffer size varies, and the client does not require the buffer
processor to consume all of the input and fill all of the output buffer. This
is useful when the implementation has access to the host API's circular buffer
and only needs to consume/fill some of it, not necessarily all of it, with each
call to the buffer processor. This is the only mode where
PaUtil_EndBufferProcessing() may not consume the whole buffer.
*/
paUtilVariableHostBufferSizePartialUsageAllowed
}PaUtilHostBufferSizeMode;
/** @brief An auxiliary data structure used internally by the buffer processor
to represent host input and output buffers. */
typedef struct PaUtilChannelDescriptor{
void *data;
unsigned int stride; /**< stride in samples, not bytes */
}PaUtilChannelDescriptor;
/** @brief The main buffer processor data structure.
Allocate one of these, initialize it with PaUtil_InitializeBufferProcessor
and terminate it with PaUtil_TerminateBufferProcessor.
*/
typedef struct {
unsigned long framesPerUserBuffer;
unsigned long framesPerHostBuffer;
PaUtilHostBufferSizeMode hostBufferSizeMode;
int useNonAdaptingProcess;
int userOutputSampleFormatIsEqualToHost;
int userInputSampleFormatIsEqualToHost;
unsigned long framesPerTempBuffer;
unsigned int inputChannelCount;
unsigned int bytesPerHostInputSample;
unsigned int bytesPerUserInputSample;
int userInputIsInterleaved;
PaUtilConverter *inputConverter;
PaUtilZeroer *inputZeroer;
unsigned int outputChannelCount;
unsigned int bytesPerHostOutputSample;
unsigned int bytesPerUserOutputSample;
int userOutputIsInterleaved;
PaUtilConverter *outputConverter;
PaUtilZeroer *outputZeroer;
unsigned long initialFramesInTempInputBuffer;
unsigned long initialFramesInTempOutputBuffer;
void *tempInputBuffer; /**< used for slips, block adaption, and conversion. */
void **tempInputBufferPtrs; /**< storage for non-interleaved buffer pointers, NULL for interleaved user input */
unsigned long framesInTempInputBuffer; /**< frames remaining in input buffer from previous adaption iteration */
void *tempOutputBuffer; /**< used for slips, block adaption, and conversion. */
void **tempOutputBufferPtrs; /**< storage for non-interleaved buffer pointers, NULL for interleaved user output */
unsigned long framesInTempOutputBuffer; /**< frames remaining in input buffer from previous adaption iteration */
PaStreamCallbackTimeInfo *timeInfo;
PaStreamCallbackFlags callbackStatusFlags;
int hostInputIsInterleaved;
unsigned long hostInputFrameCount[2];
PaUtilChannelDescriptor *hostInputChannels[2]; /**< pointers to arrays of channel descriptors.
pointers are NULL for half-duplex output processing.
hostInputChannels[i].data is NULL when the caller
calls PaUtil_SetNoInput()
*/
int hostOutputIsInterleaved;
unsigned long hostOutputFrameCount[2];
PaUtilChannelDescriptor *hostOutputChannels[2]; /**< pointers to arrays of channel descriptors.
pointers are NULL for half-duplex input processing.
hostOutputChannels[i].data is NULL when the caller
calls PaUtil_SetNoOutput()
*/
PaUtilTriangularDitherGenerator ditherGenerator;
double samplePeriod;
PaStreamCallback *streamCallback;
void *userData;
} PaUtilBufferProcessor;
/** @name Initialization, termination, resetting and info */
/*@{*/
/** Initialize a buffer processor's representation stored in a
PaUtilBufferProcessor structure. Be sure to call
PaUtil_TerminateBufferProcessor after finishing with a buffer processor.
@param bufferProcessor The buffer processor structure to initialize.
@param inputChannelCount The number of input channels as passed to
Pa_OpenStream or 0 for an output-only stream.
@param userInputSampleFormat Format of user input samples, as passed to
Pa_OpenStream. This parameter is ignored for ouput-only streams.
@param hostInputSampleFormat Format of host input samples. This parameter is
ignored for output-only streams. See note about host buffer interleave below.
@param outputChannelCount The number of output channels as passed to
Pa_OpenStream or 0 for an input-only stream.
@param userOutputSampleFormat Format of user output samples, as passed to
Pa_OpenStream. This parameter is ignored for input-only streams.
@param hostOutputSampleFormat Format of host output samples. This parameter is
ignored for input-only streams. See note about host buffer interleave below.
@param sampleRate Sample rate of the stream. The more accurate this is the
better - it is used for updating time stamps when adapting buffers.
@param streamFlags Stream flags as passed to Pa_OpenStream, this parameter is
used for selecting special sample conversion options such as clipping and
dithering.
@param framesPerUserBuffer Number of frames per user buffer, as requested
by the framesPerBuffer parameter to Pa_OpenStream. This parameter may be
zero to indicate that the user will accept any (and varying) buffer sizes.
@param framesPerHostBuffer Specifies the number of frames per host buffer
for the fixed buffer size mode, and the maximum number of frames
per host buffer for the bounded host buffer size mode. It is ignored for
the other modes.
@param hostBufferSizeMode A mode flag indicating the size variability of
host buffers that will be passed to the buffer processor. See
PaUtilHostBufferSizeMode for further details.
@param streamCallback The user stream callback passed to Pa_OpenStream.
@param userData The user data field passed to Pa_OpenStream.
@note The interleave flag is ignored for host buffer formats. Host
interleave is determined by the use of different SetInput and SetOutput
functions.
@return An error code indicating whether the initialization was successful.
If the error code is not PaNoError, the buffer processor was not initialized
and should not be used.
@see Pa_OpenStream, PaUtilHostBufferSizeMode, PaUtil_TerminateBufferProcessor
*/
PaError PaUtil_InitializeBufferProcessor( PaUtilBufferProcessor* bufferProcessor,
int inputChannelCount, PaSampleFormat userInputSampleFormat,
PaSampleFormat hostInputSampleFormat,
int outputChannelCount, PaSampleFormat userOutputSampleFormat,
PaSampleFormat hostOutputSampleFormat,
double sampleRate,
PaStreamFlags streamFlags,
unsigned long framesPerUserBuffer, /* 0 indicates don't care */
unsigned long framesPerHostBuffer,
PaUtilHostBufferSizeMode hostBufferSizeMode,
PaStreamCallback *streamCallback, void *userData );
/** Terminate a buffer processor's representation. Deallocates any temporary
buffers allocated by PaUtil_InitializeBufferProcessor.
@param bufferProcessor The buffer processor structure to terminate.
@see PaUtil_InitializeBufferProcessor.
*/
void PaUtil_TerminateBufferProcessor( PaUtilBufferProcessor* bufferProcessor );
/** Clear any internally buffered data. If you call
PaUtil_InitializeBufferProcessor in your OpenStream routine, make sure you
call PaUtil_ResetBufferProcessor in your StartStream call.
@param bufferProcessor The buffer processor to reset.
*/
void PaUtil_ResetBufferProcessor( PaUtilBufferProcessor* bufferProcessor );
/** Retrieve the input latency of a buffer processor, in frames.
@param bufferProcessor The buffer processor examine.
@return The input latency introduced by the buffer processor, in frames.
@see PaUtil_GetBufferProcessorOutputLatencyFrames
*/
unsigned long PaUtil_GetBufferProcessorInputLatencyFrames( PaUtilBufferProcessor* bufferProcessor );
/** Retrieve the output latency of a buffer processor, in frames.
@param bufferProcessor The buffer processor examine.
@return The output latency introduced by the buffer processor, in frames.
@see PaUtil_GetBufferProcessorInputLatencyFrames
*/
unsigned long PaUtil_GetBufferProcessorOutputLatencyFrames( PaUtilBufferProcessor* bufferProcessor );
/*@}*/
/** @name Host buffer pointer configuration
Functions to set host input and output buffers, used by both callback streams
and blocking read/write streams.
*/
/*@{*/
/** Set the number of frames in the input host buffer(s) specified by the
PaUtil_Set*InputChannel functions.
@param bufferProcessor The buffer processor.
@param frameCount The number of host input frames. A 0 frameCount indicates to
use the framesPerHostBuffer value passed to PaUtil_InitializeBufferProcessor.
@see PaUtil_SetNoInput, PaUtil_SetInputChannel,
PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel
*/
void PaUtil_SetInputFrameCount( PaUtilBufferProcessor* bufferProcessor,
unsigned long frameCount );
/** Indicate that no input is available. This function should be used when
priming the output of a full-duplex stream opened with the
paPrimeOutputBuffersUsingStreamCallback flag. Note that it is not necessary
to call this or any other PaUtil_Set*Input* functions for ouput-only streams.
@param bufferProcessor The buffer processor.
*/
void PaUtil_SetNoInput( PaUtilBufferProcessor* bufferProcessor );
/** Provide the buffer processor with a pointer to a host input channel.
@param bufferProcessor The buffer processor.
@param channel The channel number.
@param data The buffer.
@param stride The stride from one sample to the next, in samples. For
interleaved host buffers, the stride will usually be the same as the number of
channels in the buffer.
*/
void PaUtil_SetInputChannel( PaUtilBufferProcessor* bufferProcessor,
unsigned int channel, void *data, unsigned int stride );
/** Provide the buffer processor with a pointer to an number of interleaved
host input channels.
@param bufferProcessor The buffer processor.
@param firstChannel The first channel number.
@param data The buffer.
@param channelCount The number of interleaved channels in the buffer. If
channelCount is zero, the number of channels specified to
PaUtil_InitializeBufferProcessor will be used.
*/
void PaUtil_SetInterleavedInputChannels( PaUtilBufferProcessor* bufferProcessor,
unsigned int firstChannel, void *data, unsigned int channelCount );
/** Provide the buffer processor with a pointer to one non-interleaved host
output channel.
@param bufferProcessor The buffer processor.
@param channel The channel number.
@param data The buffer.
*/
void PaUtil_SetNonInterleavedInputChannel( PaUtilBufferProcessor* bufferProcessor,
unsigned int channel, void *data );
/** Use for the second buffer half when the input buffer is split in two halves.
@see PaUtil_SetInputFrameCount
*/
void PaUtil_Set2ndInputFrameCount( PaUtilBufferProcessor* bufferProcessor,
unsigned long frameCount );
/** Use for the second buffer half when the input buffer is split in two halves.
@see PaUtil_SetInputChannel
*/
void PaUtil_Set2ndInputChannel( PaUtilBufferProcessor* bufferProcessor,
unsigned int channel, void *data, unsigned int stride );
/** Use for the second buffer half when the input buffer is split in two halves.
@see PaUtil_SetInterleavedInputChannels
*/
void PaUtil_Set2ndInterleavedInputChannels( PaUtilBufferProcessor* bufferProcessor,
unsigned int firstChannel, void *data, unsigned int channelCount );
/** Use for the second buffer half when the input buffer is split in two halves.
@see PaUtil_SetNonInterleavedInputChannel
*/
void PaUtil_Set2ndNonInterleavedInputChannel( PaUtilBufferProcessor* bufferProcessor,
unsigned int channel, void *data );
/** Set the number of frames in the output host buffer(s) specified by the
PaUtil_Set*OutputChannel functions.
@param bufferProcessor The buffer processor.
@param frameCount The number of host output frames. A 0 frameCount indicates to
use the framesPerHostBuffer value passed to PaUtil_InitializeBufferProcessor.
@see PaUtil_SetOutputChannel, PaUtil_SetInterleavedOutputChannels,
PaUtil_SetNonInterleavedOutputChannel
*/
void PaUtil_SetOutputFrameCount( PaUtilBufferProcessor* bufferProcessor,
unsigned long frameCount );
/** Indicate that the output will be discarded. This function should be used
when implementing the paNeverDropInput mode for full duplex streams.
@param bufferProcessor The buffer processor.
*/
void PaUtil_SetNoOutput( PaUtilBufferProcessor* bufferProcessor );
/** Provide the buffer processor with a pointer to a host output channel.
@param bufferProcessor The buffer processor.
@param channel The channel number.
@param data The buffer.
@param stride The stride from one sample to the next, in samples. For
interleaved host buffers, the stride will usually be the same as the number of
channels in the buffer.
*/
void PaUtil_SetOutputChannel( PaUtilBufferProcessor* bufferProcessor,
unsigned int channel, void *data, unsigned int stride );
/** Provide the buffer processor with a pointer to a number of interleaved
host output channels.
@param bufferProcessor The buffer processor.
@param firstChannel The first channel number.
@param data The buffer.
@param channelCount The number of interleaved channels in the buffer. If
channelCount is zero, the number of channels specified to
PaUtil_InitializeBufferProcessor will be used.
*/
void PaUtil_SetInterleavedOutputChannels( PaUtilBufferProcessor* bufferProcessor,
unsigned int firstChannel, void *data, unsigned int channelCount );
/** Provide the buffer processor with a pointer to one non-interleaved host
output channel.
@param bufferProcessor The buffer processor.
@param channel The channel number.
@param data The buffer.
*/
void PaUtil_SetNonInterleavedOutputChannel( PaUtilBufferProcessor* bufferProcessor,
unsigned int channel, void *data );
/** Use for the second buffer half when the output buffer is split in two halves.
@see PaUtil_SetOutputFrameCount
*/
void PaUtil_Set2ndOutputFrameCount( PaUtilBufferProcessor* bufferProcessor,
unsigned long frameCount );
/** Use for the second buffer half when the output buffer is split in two halves.
@see PaUtil_SetOutputChannel
*/
void PaUtil_Set2ndOutputChannel( PaUtilBufferProcessor* bufferProcessor,
unsigned int channel, void *data, unsigned int stride );
/** Use for the second buffer half when the output buffer is split in two halves.
@see PaUtil_SetInterleavedOutputChannels
*/
void PaUtil_Set2ndInterleavedOutputChannels( PaUtilBufferProcessor* bufferProcessor,
unsigned int firstChannel, void *data, unsigned int channelCount );
/** Use for the second buffer half when the output buffer is split in two halves.
@see PaUtil_SetNonInterleavedOutputChannel
*/
void PaUtil_Set2ndNonInterleavedOutputChannel( PaUtilBufferProcessor* bufferProcessor,
unsigned int channel, void *data );
/*@}*/
/** @name Buffer processing functions for callback streams
*/
/*@{*/
/** Commence processing a host buffer (or a pair of host buffers in the
full-duplex case) for a callback stream.
@param bufferProcessor The buffer processor.
@param timeInfo Timing information for the first sample of the host
buffer(s). This information may be adjusted when buffer adaption is being
performed.
@param callbackStatusFlags Flags indicating whether underruns and overruns
have occurred since the last time the buffer processor was called.
*/
void PaUtil_BeginBufferProcessing( PaUtilBufferProcessor* bufferProcessor,
PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags callbackStatusFlags );
/** Finish processing a host buffer (or a pair of host buffers in the
full-duplex case) for a callback stream.
@param bufferProcessor The buffer processor.
@param callbackResult On input, indicates a previous callback result, and on
exit, the result of the user stream callback, if it is called.
On entry callbackResult should contain one of { paContinue, paComplete, or
paAbort}. If paComplete is passed, the stream callback will not be called
but any audio that was generated by previous stream callbacks will be copied
to the output buffer(s). You can check whether the buffer processor's internal
buffer is empty by calling PaUtil_IsBufferProcessorOutputEmpty.
If the stream callback is called its result is stored in *callbackResult. If
the stream callback returns paComplete or paAbort, all output buffers will be
full of valid data - some of which may be zeros to account for data that
wasn't generated by the terminating callback.
@return The number of frames processed. This usually corresponds to the
number of frames specified by the PaUtil_Set*FrameCount functions, except in
the paUtilVariableHostBufferSizePartialUsageAllowed buffer size mode when a
smaller value may be returned.
*/
unsigned long PaUtil_EndBufferProcessing( PaUtilBufferProcessor* bufferProcessor,
int *callbackResult );
/** Determine whether any callback generated output remains in the buffer
processor's internal buffers. This method may be used to determine when to
continue calling PaUtil_EndBufferProcessing() after the callback has returned
a callbackResult of paComplete.
@param bufferProcessor The buffer processor.
@return Returns non-zero when callback generated output remains in the internal
buffer and zero (0) when there internal buffer contains no callback generated
data.
*/
int PaUtil_IsBufferProcessorOutputEmpty( PaUtilBufferProcessor* bufferProcessor );
/*@}*/
/** @name Buffer processing functions for blocking read/write streams
*/
/*@{*/
/** Copy samples from host input channels set up by the PaUtil_Set*InputChannels
functions to a user supplied buffer. This function is intended for use with
blocking read/write streams. Copies the minimum of the number of
user frames (specified by the frameCount parameter) and the number of available
host frames (specified in a previous call to SetInputFrameCount()).
@param bufferProcessor The buffer processor.
@param buffer A pointer to the user buffer pointer, or a pointer to a pointer
to an array of user buffer pointers for a non-interleaved stream. It is
important that this parameter points to a copy of the user buffer pointers,
not to the actual user buffer pointers, because this function updates the
pointers before returning.
@param frameCount The number of frames of data in the buffer(s) pointed to by
the buffer parameter.
@return The number of frames copied. The buffer pointer(s) pointed to by the
buffer parameter are advanced to point to the frame(s) following the last one
filled.
*/
unsigned long PaUtil_CopyInput( PaUtilBufferProcessor* bufferProcessor,
void **buffer, unsigned long frameCount );
/* Copy samples from a user supplied buffer to host output channels set up by
the PaUtil_Set*OutputChannels functions. This function is intended for use with
blocking read/write streams. Copies the minimum of the number of
user frames (specified by the frameCount parameter) and the number of
host frames (specified in a previous call to SetOutputFrameCount()).
@param bufferProcessor The buffer processor.
@param buffer A pointer to the user buffer pointer, or a pointer to a pointer
to an array of user buffer pointers for a non-interleaved stream. It is
important that this parameter points to a copy of the user buffer pointers,
not to the actual user buffer pointers, because this function updates the
pointers before returning.
@param frameCount The number of frames of data in the buffer(s) pointed to by
the buffer parameter.
@return The number of frames copied. The buffer pointer(s) pointed to by the
buffer parameter are advanced to point to the frame(s) following the last one
copied.
*/
unsigned long PaUtil_CopyOutput( PaUtilBufferProcessor* bufferProcessor,
const void ** buffer, unsigned long frameCount );
/* Zero samples in host output channels set up by the PaUtil_Set*OutputChannels
functions. This function is useful for flushing streams.
Zeros the minimum of frameCount and the number of host frames specified in a
previous call to SetOutputFrameCount().
@param bufferProcessor The buffer processor.
@param frameCount The maximum number of frames to zero.
@return The number of frames zeroed.
*/
unsigned long PaUtil_ZeroOutput( PaUtilBufferProcessor* bufferProcessor,
unsigned long frameCount );
/*@}*/
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_PROCESS_H */

View file

@ -0,0 +1,237 @@
/*
* $Id$
* Portable Audio I/O Library
* Ring Buffer utility.
*
* Author: Phil Burk, http://www.softsynth.com
* modified for SMP safety on Mac OS X by Bjorn Roche
* modified for SMP safety on Linux by Leland Lucius
* also, allowed for const where possible
* modified for multiple-byte-sized data elements by Sven Fischer
*
* Note that this is safe only for a single-thread reader and a
* single-thread writer.
*
* This program uses the PortAudio Portable Audio Library.
* For more information see: http://www.portaudio.com
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/**
@file
@ingroup common_src
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "pa_ringbuffer.h"
#include <string.h>
#include "pa_memorybarrier.h"
/***************************************************************************
* Initialize FIFO.
* elementCount must be power of 2, returns -1 if not.
*/
ring_buffer_size_t PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementSizeBytes, ring_buffer_size_t elementCount, void *dataPtr )
{
if( ((elementCount-1) & elementCount) != 0) return -1; /* Not Power of two. */
rbuf->bufferSize = elementCount;
rbuf->buffer = (char *)dataPtr;
PaUtil_FlushRingBuffer( rbuf );
rbuf->bigMask = (elementCount*2)-1;
rbuf->smallMask = (elementCount)-1;
rbuf->elementSizeBytes = elementSizeBytes;
return 0;
}
/***************************************************************************
** Return number of elements available for reading. */
ring_buffer_size_t PaUtil_GetRingBufferReadAvailable( const PaUtilRingBuffer *rbuf )
{
return ( (rbuf->writeIndex - rbuf->readIndex) & rbuf->bigMask );
}
/***************************************************************************
** Return number of elements available for writing. */
ring_buffer_size_t PaUtil_GetRingBufferWriteAvailable( const PaUtilRingBuffer *rbuf )
{
return ( rbuf->bufferSize - PaUtil_GetRingBufferReadAvailable(rbuf));
}
/***************************************************************************
** Clear buffer. Should only be called when buffer is NOT being read or written. */
void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf )
{
rbuf->writeIndex = rbuf->readIndex = 0;
}
/***************************************************************************
** Get address of region(s) to which we can write data.
** If the region is contiguous, size2 will be zero.
** If non-contiguous, size2 will be the size of second region.
** Returns room available to be written or elementCount, whichever is smaller.
*/
ring_buffer_size_t PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
void **dataPtr1, ring_buffer_size_t *sizePtr1,
void **dataPtr2, ring_buffer_size_t *sizePtr2 )
{
ring_buffer_size_t index;
ring_buffer_size_t available = PaUtil_GetRingBufferWriteAvailable( rbuf );
if( elementCount > available ) elementCount = available;
/* Check to see if write is not contiguous. */
index = rbuf->writeIndex & rbuf->smallMask;
if( (index + elementCount) > rbuf->bufferSize )
{
/* Write data in two blocks that wrap the buffer. */
ring_buffer_size_t firstHalf = rbuf->bufferSize - index;
*dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
*sizePtr1 = firstHalf;
*dataPtr2 = &rbuf->buffer[0];
*sizePtr2 = elementCount - firstHalf;
}
else
{
*dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
*sizePtr1 = elementCount;
*dataPtr2 = NULL;
*sizePtr2 = 0;
}
if( available )
PaUtil_FullMemoryBarrier(); /* (write-after-read) => full barrier */
return elementCount;
}
/***************************************************************************
*/
ring_buffer_size_t PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount )
{
/* ensure that previous writes are seen before we update the write index
(write after write)
*/
PaUtil_WriteMemoryBarrier();
return rbuf->writeIndex = (rbuf->writeIndex + elementCount) & rbuf->bigMask;
}
/***************************************************************************
** Get address of region(s) from which we can read data.
** If the region is contiguous, size2 will be zero.
** If non-contiguous, size2 will be the size of second region.
** Returns room available to be read or elementCount, whichever is smaller.
*/
ring_buffer_size_t PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
void **dataPtr1, ring_buffer_size_t *sizePtr1,
void **dataPtr2, ring_buffer_size_t *sizePtr2 )
{
ring_buffer_size_t index;
ring_buffer_size_t available = PaUtil_GetRingBufferReadAvailable( rbuf ); /* doesn't use memory barrier */
if( elementCount > available ) elementCount = available;
/* Check to see if read is not contiguous. */
index = rbuf->readIndex & rbuf->smallMask;
if( (index + elementCount) > rbuf->bufferSize )
{
/* Write data in two blocks that wrap the buffer. */
ring_buffer_size_t firstHalf = rbuf->bufferSize - index;
*dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
*sizePtr1 = firstHalf;
*dataPtr2 = &rbuf->buffer[0];
*sizePtr2 = elementCount - firstHalf;
}
else
{
*dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
*sizePtr1 = elementCount;
*dataPtr2 = NULL;
*sizePtr2 = 0;
}
if( available )
PaUtil_ReadMemoryBarrier(); /* (read-after-read) => read barrier */
return elementCount;
}
/***************************************************************************
*/
ring_buffer_size_t PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount )
{
/* ensure that previous reads (copies out of the ring buffer) are always completed before updating (writing) the read index.
(write-after-read) => full barrier
*/
PaUtil_FullMemoryBarrier();
return rbuf->readIndex = (rbuf->readIndex + elementCount) & rbuf->bigMask;
}
/***************************************************************************
** Return elements written. */
ring_buffer_size_t PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, ring_buffer_size_t elementCount )
{
ring_buffer_size_t size1, size2, numWritten;
void *data1, *data2;
numWritten = PaUtil_GetRingBufferWriteRegions( rbuf, elementCount, &data1, &size1, &data2, &size2 );
if( size2 > 0 )
{
memcpy( data1, data, size1*rbuf->elementSizeBytes );
data = ((char *)data) + size1*rbuf->elementSizeBytes;
memcpy( data2, data, size2*rbuf->elementSizeBytes );
}
else
{
memcpy( data1, data, size1*rbuf->elementSizeBytes );
}
PaUtil_AdvanceRingBufferWriteIndex( rbuf, numWritten );
return numWritten;
}
/***************************************************************************
** Return elements read. */
ring_buffer_size_t PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, ring_buffer_size_t elementCount )
{
ring_buffer_size_t size1, size2, numRead;
void *data1, *data2;
numRead = PaUtil_GetRingBufferReadRegions( rbuf, elementCount, &data1, &size1, &data2, &size2 );
if( size2 > 0 )
{
memcpy( data, data1, size1*rbuf->elementSizeBytes );
data = ((char *)data) + size1*rbuf->elementSizeBytes;
memcpy( data, data2, size2*rbuf->elementSizeBytes );
}
else
{
memcpy( data, data1, size1*rbuf->elementSizeBytes );
}
PaUtil_AdvanceRingBufferReadIndex( rbuf, numRead );
return numRead;
}

View file

@ -0,0 +1,236 @@
#ifndef PA_RINGBUFFER_H
#define PA_RINGBUFFER_H
/*
* $Id$
* Portable Audio I/O Library
* Ring Buffer utility.
*
* Author: Phil Burk, http://www.softsynth.com
* modified for SMP safety on OS X by Bjorn Roche.
* also allowed for const where possible.
* modified for multiple-byte-sized data elements by Sven Fischer
*
* Note that this is safe only for a single-thread reader
* and a single-thread writer.
*
* This program is distributed with the PortAudio Portable Audio Library.
* For more information see: http://www.portaudio.com
* Copyright (c) 1999-2000 Ross Bencina and Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Single-reader single-writer lock-free ring buffer
PaUtilRingBuffer is a ring buffer used to transport samples between
different execution contexts (threads, OS callbacks, interrupt handlers)
without requiring the use of any locks. This only works when there is
a single reader and a single writer (ie. one thread or callback writes
to the ring buffer, another thread or callback reads from it).
The PaUtilRingBuffer structure manages a ring buffer containing N
elements, where N must be a power of two. An element may be any size
(specified in bytes).
The memory area used to store the buffer elements must be allocated by
the client prior to calling PaUtil_InitializeRingBuffer() and must outlive
the use of the ring buffer.
@note The ring buffer functions are not normally exposed in the PortAudio libraries.
If you want to call them then you will need to add pa_ringbuffer.c to your application source code.
*/
#if defined(__APPLE__)
#include <sys/types.h>
typedef int32_t ring_buffer_size_t;
#elif defined( __GNUC__ )
typedef long ring_buffer_size_t;
#elif (_MSC_VER >= 1400)
typedef long ring_buffer_size_t;
#elif defined(_MSC_VER) || defined(__BORLANDC__)
typedef long ring_buffer_size_t;
#else
typedef long ring_buffer_size_t;
#endif
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
typedef struct PaUtilRingBuffer
{
ring_buffer_size_t bufferSize; /**< Number of elements in FIFO. Power of 2. Set by PaUtil_InitRingBuffer. */
volatile ring_buffer_size_t writeIndex; /**< Index of next writable element. Set by PaUtil_AdvanceRingBufferWriteIndex. */
volatile ring_buffer_size_t readIndex; /**< Index of next readable element. Set by PaUtil_AdvanceRingBufferReadIndex. */
ring_buffer_size_t bigMask; /**< Used for wrapping indices with extra bit to distinguish full/empty. */
ring_buffer_size_t smallMask; /**< Used for fitting indices to buffer. */
ring_buffer_size_t elementSizeBytes; /**< Number of bytes per element. */
char *buffer; /**< Pointer to the buffer containing the actual data. */
}PaUtilRingBuffer;
/** Initialize Ring Buffer to empty state ready to have elements written to it.
@param rbuf The ring buffer.
@param elementSizeBytes The size of a single data element in bytes.
@param elementCount The number of elements in the buffer (must be a power of 2).
@param dataPtr A pointer to a previously allocated area where the data
will be maintained. It must be elementCount*elementSizeBytes long.
@return -1 if elementCount is not a power of 2, otherwise 0.
*/
ring_buffer_size_t PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementSizeBytes, ring_buffer_size_t elementCount, void *dataPtr );
/** Reset buffer to empty. Should only be called when buffer is NOT being read or written.
@param rbuf The ring buffer.
*/
void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf );
/** Retrieve the number of elements available in the ring buffer for writing.
@param rbuf The ring buffer.
@return The number of elements available for writing.
*/
ring_buffer_size_t PaUtil_GetRingBufferWriteAvailable( const PaUtilRingBuffer *rbuf );
/** Retrieve the number of elements available in the ring buffer for reading.
@param rbuf The ring buffer.
@return The number of elements available for reading.
*/
ring_buffer_size_t PaUtil_GetRingBufferReadAvailable( const PaUtilRingBuffer *rbuf );
/** Write data to the ring buffer.
@param rbuf The ring buffer.
@param data The address of new data to write to the buffer.
@param elementCount The number of elements to be written.
@return The number of elements written.
*/
ring_buffer_size_t PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, ring_buffer_size_t elementCount );
/** Read data from the ring buffer.
@param rbuf The ring buffer.
@param data The address where the data should be stored.
@param elementCount The number of elements to be read.
@return The number of elements read.
*/
ring_buffer_size_t PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, ring_buffer_size_t elementCount );
/** Get address of region(s) to which we can write data.
@param rbuf The ring buffer.
@param elementCount The number of elements desired.
@param dataPtr1 The address where the first (or only) region pointer will be
stored.
@param sizePtr1 The address where the first (or only) region length will be
stored.
@param dataPtr2 The address where the second region pointer will be stored if
the first region is too small to satisfy elementCount.
@param sizePtr2 The address where the second region length will be stored if
the first region is too small to satisfy elementCount.
@return The room available to be written or elementCount, whichever is smaller.
*/
ring_buffer_size_t PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
void **dataPtr1, ring_buffer_size_t *sizePtr1,
void **dataPtr2, ring_buffer_size_t *sizePtr2 );
/** Advance the write index to the next location to be written.
@param rbuf The ring buffer.
@param elementCount The number of elements to advance.
@return The new position.
*/
ring_buffer_size_t PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount );
/** Get address of region(s) from which we can read data.
@param rbuf The ring buffer.
@param elementCount The number of elements desired.
@param dataPtr1 The address where the first (or only) region pointer will be
stored.
@param sizePtr1 The address where the first (or only) region length will be
stored.
@param dataPtr2 The address where the second region pointer will be stored if
the first region is too small to satisfy elementCount.
@param sizePtr2 The address where the second region length will be stored if
the first region is too small to satisfy elementCount.
@return The number of elements available for reading.
*/
ring_buffer_size_t PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
void **dataPtr1, ring_buffer_size_t *sizePtr1,
void **dataPtr2, ring_buffer_size_t *sizePtr2 );
/** Advance the read index to the next location to be read.
@param rbuf The ring buffer.
@param elementCount The number of elements to advance.
@return The new position.
*/
ring_buffer_size_t PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount );
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_RINGBUFFER_H */

View file

@ -0,0 +1,150 @@
/*
* $Id$
* Portable Audio I/O Library
* stream interface
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 2008 Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Stream interfaces, representation structures and helper functions
used to interface between pa_front.c host API implementations.
*/
#include "pa_stream.h"
void PaUtil_InitializeStreamInterface( PaUtilStreamInterface *streamInterface,
PaError (*Close)( PaStream* ),
PaError (*Start)( PaStream* ),
PaError (*Stop)( PaStream* ),
PaError (*Abort)( PaStream* ),
PaError (*IsStopped)( PaStream* ),
PaError (*IsActive)( PaStream* ),
PaTime (*GetTime)( PaStream* ),
double (*GetCpuLoad)( PaStream* ),
PaError (*Read)( PaStream*, void *, unsigned long ),
PaError (*Write)( PaStream*, const void *, unsigned long ),
signed long (*GetReadAvailable)( PaStream* ),
signed long (*GetWriteAvailable)( PaStream* ) )
{
streamInterface->Close = Close;
streamInterface->Start = Start;
streamInterface->Stop = Stop;
streamInterface->Abort = Abort;
streamInterface->IsStopped = IsStopped;
streamInterface->IsActive = IsActive;
streamInterface->GetTime = GetTime;
streamInterface->GetCpuLoad = GetCpuLoad;
streamInterface->Read = Read;
streamInterface->Write = Write;
streamInterface->GetReadAvailable = GetReadAvailable;
streamInterface->GetWriteAvailable = GetWriteAvailable;
}
void PaUtil_InitializeStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation,
PaUtilStreamInterface *streamInterface,
PaStreamCallback *streamCallback,
void *userData )
{
streamRepresentation->magic = PA_STREAM_MAGIC;
streamRepresentation->nextOpenStream = 0;
streamRepresentation->streamInterface = streamInterface;
streamRepresentation->streamCallback = streamCallback;
streamRepresentation->streamFinishedCallback = 0;
streamRepresentation->userData = userData;
streamRepresentation->streamInfo.inputLatency = 0.;
streamRepresentation->streamInfo.outputLatency = 0.;
streamRepresentation->streamInfo.sampleRate = 0.;
}
void PaUtil_TerminateStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation )
{
streamRepresentation->magic = 0;
}
PaError PaUtil_DummyRead( PaStream* stream,
void *buffer,
unsigned long frames )
{
(void)stream; /* unused parameter */
(void)buffer; /* unused parameter */
(void)frames; /* unused parameter */
return paCanNotReadFromACallbackStream;
}
PaError PaUtil_DummyWrite( PaStream* stream,
const void *buffer,
unsigned long frames )
{
(void)stream; /* unused parameter */
(void)buffer; /* unused parameter */
(void)frames; /* unused parameter */
return paCanNotWriteToACallbackStream;
}
signed long PaUtil_DummyGetReadAvailable( PaStream* stream )
{
(void)stream; /* unused parameter */
return paCanNotReadFromACallbackStream;
}
signed long PaUtil_DummyGetWriteAvailable( PaStream* stream )
{
(void)stream; /* unused parameter */
return paCanNotWriteToACallbackStream;
}
double PaUtil_DummyGetCpuLoad( PaStream* stream )
{
(void)stream; /* unused parameter */
return 0.0;
}

View file

@ -0,0 +1,205 @@
#ifndef PA_STREAM_H
#define PA_STREAM_H
/*
* $Id$
* Portable Audio I/O Library
* stream interface
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2008 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Stream interfaces, representation structures and helper functions
used to interface between pa_front.c host API implementations.
*/
#include "portaudio.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
#define PA_STREAM_MAGIC (0x18273645)
/** A structure representing an (abstract) interface to a host API. Contains
pointers to functions which implement the interface.
All PaStreamInterface functions are guaranteed to be called with a non-null,
valid stream parameter.
*/
typedef struct {
PaError (*Close)( PaStream* stream );
PaError (*Start)( PaStream *stream );
PaError (*Stop)( PaStream *stream );
PaError (*Abort)( PaStream *stream );
PaError (*IsStopped)( PaStream *stream );
PaError (*IsActive)( PaStream *stream );
PaTime (*GetTime)( PaStream *stream );
double (*GetCpuLoad)( PaStream* stream );
PaError (*Read)( PaStream* stream, void *buffer, unsigned long frames );
PaError (*Write)( PaStream* stream, const void *buffer, unsigned long frames );
signed long (*GetReadAvailable)( PaStream* stream );
signed long (*GetWriteAvailable)( PaStream* stream );
} PaUtilStreamInterface;
/** Initialize the fields of a PaUtilStreamInterface structure.
*/
void PaUtil_InitializeStreamInterface( PaUtilStreamInterface *streamInterface,
PaError (*Close)( PaStream* ),
PaError (*Start)( PaStream* ),
PaError (*Stop)( PaStream* ),
PaError (*Abort)( PaStream* ),
PaError (*IsStopped)( PaStream* ),
PaError (*IsActive)( PaStream* ),
PaTime (*GetTime)( PaStream* ),
double (*GetCpuLoad)( PaStream* ),
PaError (*Read)( PaStream* stream, void *buffer, unsigned long frames ),
PaError (*Write)( PaStream* stream, const void *buffer, unsigned long frames ),
signed long (*GetReadAvailable)( PaStream* stream ),
signed long (*GetWriteAvailable)( PaStream* stream ) );
/** Dummy Read function for use in interfaces to a callback based streams.
Pass to the Read parameter of PaUtil_InitializeStreamInterface.
@return An error code indicating that the function has no effect
because the stream is a callback stream.
*/
PaError PaUtil_DummyRead( PaStream* stream,
void *buffer,
unsigned long frames );
/** Dummy Write function for use in an interfaces to callback based streams.
Pass to the Write parameter of PaUtil_InitializeStreamInterface.
@return An error code indicating that the function has no effect
because the stream is a callback stream.
*/
PaError PaUtil_DummyWrite( PaStream* stream,
const void *buffer,
unsigned long frames );
/** Dummy GetReadAvailable function for use in interfaces to callback based
streams. Pass to the GetReadAvailable parameter of PaUtil_InitializeStreamInterface.
@return An error code indicating that the function has no effect
because the stream is a callback stream.
*/
signed long PaUtil_DummyGetReadAvailable( PaStream* stream );
/** Dummy GetWriteAvailable function for use in interfaces to callback based
streams. Pass to the GetWriteAvailable parameter of PaUtil_InitializeStreamInterface.
@return An error code indicating that the function has no effect
because the stream is a callback stream.
*/
signed long PaUtil_DummyGetWriteAvailable( PaStream* stream );
/** Dummy GetCpuLoad function for use in an interface to a read/write stream.
Pass to the GetCpuLoad parameter of PaUtil_InitializeStreamInterface.
@return Returns 0.
*/
double PaUtil_DummyGetCpuLoad( PaStream* stream );
/** Non host specific data for a stream. This data is used by pa_front to
forward to the appropriate functions in the streamInterface structure.
*/
typedef struct PaUtilStreamRepresentation {
unsigned long magic; /**< set to PA_STREAM_MAGIC */
struct PaUtilStreamRepresentation *nextOpenStream; /**< field used by multi-api code */
PaUtilStreamInterface *streamInterface;
PaStreamCallback *streamCallback;
PaStreamFinishedCallback *streamFinishedCallback;
void *userData;
PaStreamInfo streamInfo;
} PaUtilStreamRepresentation;
/** Initialize a PaUtilStreamRepresentation structure.
@see PaUtil_InitializeStreamRepresentation
*/
void PaUtil_InitializeStreamRepresentation(
PaUtilStreamRepresentation *streamRepresentation,
PaUtilStreamInterface *streamInterface,
PaStreamCallback *streamCallback,
void *userData );
/** Clean up a PaUtilStreamRepresentation structure previously initialized
by a call to PaUtil_InitializeStreamRepresentation.
@see PaUtil_InitializeStreamRepresentation
*/
void PaUtil_TerminateStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation );
/** Check that the stream pointer is valid.
@return Returns paNoError if the stream pointer appears to be OK, otherwise
returns an error indicating the cause of failure.
*/
PaError PaUtil_ValidateStreamPointer( PaStream *stream );
/** Cast an opaque stream pointer into a pointer to a PaUtilStreamRepresentation.
@see PaUtilStreamRepresentation
*/
#define PA_STREAM_REP( stream )\
((PaUtilStreamRepresentation*) (stream) )
/** Cast an opaque stream pointer into a pointer to a PaUtilStreamInterface.
@see PaUtilStreamRepresentation, PaUtilStreamInterface
*/
#define PA_STREAM_INTERFACE( stream )\
PA_STREAM_REP( (stream) )->streamInterface
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_STREAM_H */

View file

@ -0,0 +1,238 @@
/*
* $Id$
* Portable Audio I/O Library Trace Facility
* Store trace information in real-time for later printing.
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2000 Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Real-time safe event trace logging facility for debugging.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>
#include "pa_trace.h"
#include "pa_util.h"
#include "pa_debugprint.h"
#if PA_TRACE_REALTIME_EVENTS
static char const *traceTextArray[PA_MAX_TRACE_RECORDS];
static int traceIntArray[PA_MAX_TRACE_RECORDS];
static int traceIndex = 0;
static int traceBlock = 0;
/*********************************************************************/
void PaUtil_ResetTraceMessages()
{
traceIndex = 0;
}
/*********************************************************************/
void PaUtil_DumpTraceMessages()
{
int i;
int messageCount = (traceIndex < PA_MAX_TRACE_RECORDS) ? traceIndex : PA_MAX_TRACE_RECORDS;
printf("DumpTraceMessages: traceIndex = %d\n", traceIndex );
for( i=0; i<messageCount; i++ )
{
printf("%3d: %s = 0x%08X\n",
i, traceTextArray[i], traceIntArray[i] );
}
PaUtil_ResetTraceMessages();
fflush(stdout);
}
/*********************************************************************/
void PaUtil_AddTraceMessage( const char *msg, int data )
{
if( (traceIndex == PA_MAX_TRACE_RECORDS) && (traceBlock == 0) )
{
traceBlock = 1;
/* PaUtil_DumpTraceMessages(); */
}
else if( traceIndex < PA_MAX_TRACE_RECORDS )
{
traceTextArray[traceIndex] = msg;
traceIntArray[traceIndex] = data;
traceIndex++;
}
}
/************************************************************************/
/* High performance log alternative */
/************************************************************************/
typedef unsigned long long PaUint64;
typedef struct __PaHighPerformanceLog
{
unsigned magik;
int writePtr;
int readPtr;
int size;
double refTime;
char* data;
} PaHighPerformanceLog;
static const unsigned kMagik = 0xcafebabe;
#define USEC_PER_SEC (1000000ULL)
int PaUtil_InitializeHighSpeedLog( LogHandle* phLog, unsigned maxSizeInBytes )
{
PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)PaUtil_AllocateMemory(sizeof(PaHighPerformanceLog));
if (pLog == 0)
{
return paInsufficientMemory;
}
assert(phLog != 0);
*phLog = pLog;
pLog->data = (char*)PaUtil_AllocateMemory(maxSizeInBytes);
if (pLog->data == 0)
{
PaUtil_FreeMemory(pLog);
return paInsufficientMemory;
}
pLog->magik = kMagik;
pLog->size = maxSizeInBytes;
pLog->refTime = PaUtil_GetTime();
return paNoError;
}
void PaUtil_ResetHighSpeedLogTimeRef( LogHandle hLog )
{
PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;
assert(pLog->magik == kMagik);
pLog->refTime = PaUtil_GetTime();
}
typedef struct __PaLogEntryHeader
{
int size;
double timeStamp;
} PaLogEntryHeader;
#ifdef __APPLE__
#define _vsnprintf vsnprintf
#define min(a,b) ((a)<(b)?(a):(b))
#endif
int PaUtil_AddHighSpeedLogMessage( LogHandle hLog, const char* fmt, ... )
{
va_list l;
int n = 0;
PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;
if (pLog != 0)
{
PaLogEntryHeader* pHeader;
char* p;
int maxN;
assert(pLog->magik == kMagik);
pHeader = (PaLogEntryHeader*)( pLog->data + pLog->writePtr );
p = (char*)( pHeader + 1 );
maxN = pLog->size - pLog->writePtr - 2 * sizeof(PaLogEntryHeader);
pHeader->timeStamp = PaUtil_GetTime() - pLog->refTime;
if (maxN > 0)
{
if (maxN > 32)
{
va_start(l, fmt);
n = _vsnprintf(p, min(1024, maxN), fmt, l);
va_end(l);
}
else {
n = sprintf(p, "End of log...");
}
n = ((n + sizeof(unsigned)) & ~(sizeof(unsigned)-1)) + sizeof(PaLogEntryHeader);
pHeader->size = n;
#if 0
PaUtil_DebugPrint("%05u.%03u: %s\n", pHeader->timeStamp/1000, pHeader->timeStamp%1000, p);
#endif
pLog->writePtr += n;
}
}
return n;
}
void PaUtil_DumpHighSpeedLog( LogHandle hLog, const char* fileName )
{
FILE* f = (fileName != NULL) ? fopen(fileName, "w") : stdout;
unsigned localWritePtr;
PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;
assert(pLog->magik == kMagik);
localWritePtr = pLog->writePtr;
while (pLog->readPtr != localWritePtr)
{
const PaLogEntryHeader* pHeader = (const PaLogEntryHeader*)( pLog->data + pLog->readPtr );
const char* p = (const char*)( pHeader + 1 );
const PaUint64 ts = (const PaUint64)( pHeader->timeStamp * USEC_PER_SEC );
assert(pHeader->size < (1024+sizeof(unsigned)+sizeof(PaLogEntryHeader)));
fprintf(f, "%05u.%03u: %s\n", (unsigned)(ts/1000), (unsigned)(ts%1000), p);
pLog->readPtr += pHeader->size;
}
if (f != stdout)
{
fclose(f);
}
}
void PaUtil_DiscardHighSpeedLog( LogHandle hLog )
{
PaHighPerformanceLog* pLog = (PaHighPerformanceLog*)hLog;
assert(pLog->magik == kMagik);
PaUtil_FreeMemory(pLog->data);
PaUtil_FreeMemory(pLog);
}
#else
/* This stub was added so that this file will generate a symbol.
* Otherwise linker/archiver programs will complain.
*/
int PaUtil_TraceStubToSatisfyLinker(void)
{
return 0;
}
#endif /* TRACE_REALTIME_EVENTS */

View file

@ -0,0 +1,117 @@
#ifndef PA_TRACE_H
#define PA_TRACE_H
/*
* $Id$
* Portable Audio I/O Library Trace Facility
* Store trace information in real-time for later printing.
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2000 Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Real-time safe event trace logging facility for debugging.
Allows data to be logged to a fixed size trace buffer in a real-time
execution context (such as at interrupt time). Each log entry consists
of a message comprising a string pointer and an int. The trace buffer
may be dumped to stdout later.
This facility is only active if PA_TRACE_REALTIME_EVENTS is set to 1,
otherwise the trace functions expand to no-ops.
@fn PaUtil_ResetTraceMessages
@brief Clear the trace buffer.
@fn PaUtil_AddTraceMessage
@brief Add a message to the trace buffer. A message consists of string and an int.
@param msg The string pointer must remain valid until PaUtil_DumpTraceMessages
is called. As a result, usually only string literals should be passed as
the msg parameter.
@fn PaUtil_DumpTraceMessages
@brief Print all messages in the trace buffer to stdout and clear the trace buffer.
*/
#ifndef PA_TRACE_REALTIME_EVENTS
#define PA_TRACE_REALTIME_EVENTS (0) /**< Set to 1 to enable logging using the trace functions defined below */
#endif
#ifndef PA_MAX_TRACE_RECORDS
#define PA_MAX_TRACE_RECORDS (2048) /**< Maximum number of records stored in trace buffer */
#endif
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
#if PA_TRACE_REALTIME_EVENTS
void PaUtil_ResetTraceMessages();
void PaUtil_AddTraceMessage( const char *msg, int data );
void PaUtil_DumpTraceMessages();
/* Alternative interface */
typedef void* LogHandle;
int PaUtil_InitializeHighSpeedLog(LogHandle* phLog, unsigned maxSizeInBytes);
void PaUtil_ResetHighSpeedLogTimeRef(LogHandle hLog);
int PaUtil_AddHighSpeedLogMessage(LogHandle hLog, const char* fmt, ...);
void PaUtil_DumpHighSpeedLog(LogHandle hLog, const char* fileName);
void PaUtil_DiscardHighSpeedLog(LogHandle hLog);
#else
#define PaUtil_ResetTraceMessages() /* noop */
#define PaUtil_AddTraceMessage(msg,data) /* noop */
#define PaUtil_DumpTraceMessages() /* noop */
#define PaUtil_InitializeHighSpeedLog(phLog, maxSizeInBytes) (0)
#define PaUtil_ResetHighSpeedLogTimeRef(hLog)
#define PaUtil_AddHighSpeedLogMessage(...) (0)
#define PaUtil_DumpHighSpeedLog(hLog, fileName)
#define PaUtil_DiscardHighSpeedLog(hLog)
#endif
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_TRACE_H */

View file

@ -0,0 +1,107 @@
#ifndef PA_TYPES_H
#define PA_TYPES_H
/*
* Portable Audio I/O Library
* integer type definitions
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2006 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Definition of 16 and 32 bit integer types (PaInt16, PaInt32 etc)
SIZEOF_SHORT, SIZEOF_INT and SIZEOF_LONG are set by the configure script
when it is used. Otherwise we default to the common 32 bit values, if your
platform doesn't use configure, and doesn't use the default values below
you will need to explicitly define these symbols in your make file.
A PA_VALIDATE_SIZES macro is provided to assert that the values set in this
file are correct.
*/
#ifndef SIZEOF_SHORT
#define SIZEOF_SHORT 2
#endif
#ifndef SIZEOF_INT
#define SIZEOF_INT 4
#endif
#ifndef SIZEOF_LONG
#define SIZEOF_LONG 4
#endif
#if SIZEOF_SHORT == 2
typedef signed short PaInt16;
typedef unsigned short PaUint16;
#elif SIZEOF_INT == 2
typedef signed int PaInt16;
typedef unsigned int PaUint16;
#else
#error pa_types.h was unable to determine which type to use for 16bit integers on the target platform
#endif
#if SIZEOF_SHORT == 4
typedef signed short PaInt32;
typedef unsigned short PaUint32;
#elif SIZEOF_INT == 4
typedef signed int PaInt32;
typedef unsigned int PaUint32;
#elif SIZEOF_LONG == 4
typedef signed long PaInt32;
typedef unsigned long PaUint32;
#else
#error pa_types.h was unable to determine which type to use for 32bit integers on the target platform
#endif
/* PA_VALIDATE_TYPE_SIZES compares the size of the integer types at runtime to
ensure that PortAudio was configured correctly, and raises an assertion if
they don't match the expected values. <assert.h> must be included in the
context in which this macro is used.
*/
#define PA_VALIDATE_TYPE_SIZES \
{ \
assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaUint16 ) == 2 ); \
assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaInt16 ) == 2 ); \
assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaUint32 ) == 4 ); \
assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaInt32 ) == 4 ); \
}
#endif /* PA_TYPES_H */

View file

@ -0,0 +1,159 @@
#ifndef PA_UTIL_H
#define PA_UTIL_H
/*
* $Id$
* Portable Audio I/O Library implementation utilities header
* common implementation utilities and interfaces
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2008 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Prototypes for utility functions used by PortAudio implementations.
Some functions declared here are defined in pa_front.c while others
are implemented separately for each platform.
*/
#include "portaudio.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
struct PaUtilHostApiRepresentation;
/** Retrieve a specific host API representation. This function can be used
by implementations to retrieve a pointer to their representation in
host api specific extension functions which aren't passed a rep pointer
by pa_front.c.
@param hostApi A pointer to a host API representation pointer. Upon success
this will receive the requested representation pointer.
@param type A valid host API type identifier.
@returns An error code. If the result is PaNoError then a pointer to the
requested host API representation will be stored in *hostApi. If the host API
specified by type is not found, this function returns paHostApiNotFound.
*/
PaError PaUtil_GetHostApiRepresentation( struct PaUtilHostApiRepresentation **hostApi,
PaHostApiTypeId type );
/** Convert a PortAudio device index into a host API specific device index.
@param hostApiDevice Pointer to a device index, on success this will receive the
converted device index value.
@param device The PortAudio device index to convert.
@param hostApi The host api which the index should be converted for.
@returns On success returns PaNoError and places the converted index in the
hostApiDevice parameter.
*/
PaError PaUtil_DeviceIndexToHostApiDeviceIndex(
PaDeviceIndex *hostApiDevice, PaDeviceIndex device,
struct PaUtilHostApiRepresentation *hostApi );
/** Set the host error information returned by Pa_GetLastHostErrorInfo. This
function and the paUnanticipatedHostError error code should be used as a
last resort. Implementors should use existing PA error codes where possible,
or nominate new ones. Note that at it is always better to use
PaUtil_SetLastHostErrorInfo() and paUnanticipatedHostError than to return an
ambiguous or inaccurate PaError code.
@param hostApiType The host API which encountered the error (ie of the caller)
@param errorCode The error code returned by the native API function.
@param errorText A string describing the error. PaUtil_SetLastHostErrorInfo
makes a copy of the string, so it is not necessary for the pointer to remain
valid after the call to PaUtil_SetLastHostErrorInfo() returns.
*/
void PaUtil_SetLastHostErrorInfo( PaHostApiTypeId hostApiType, long errorCode,
const char *errorText );
/* the following functions are implemented in a platform platform specific
.c file
*/
/** Allocate size bytes, guaranteed to be aligned to a FIXME byte boundary */
void *PaUtil_AllocateMemory( long size );
/** Release block if non-NULL. block may be NULL */
void PaUtil_FreeMemory( void *block );
/** Return the number of currently allocated blocks. This function can be
used for detecting memory leaks.
@note Allocations will only be tracked if PA_TRACK_MEMORY is #defined. If
it isn't, this function will always return 0.
*/
int PaUtil_CountCurrentlyAllocatedBlocks( void );
/** Initialize the clock used by PaUtil_GetTime(). Call this before calling
PaUtil_GetTime.
@see PaUtil_GetTime
*/
void PaUtil_InitializeClock( void );
/** Return the system time in seconds. Used to implement CPU load functions
@see PaUtil_InitializeClock
*/
double PaUtil_GetTime( void );
/* void Pa_Sleep( long msec ); must also be implemented in per-platform .c file */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PA_UTIL_H */

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,147 @@
ASIO-README.txt
This document contains information to help you compile PortAudio with
ASIO support. If you find any omissions or errors in this document
please notify us on the PortAudio mailing list.
NOTE: The Macintosh sections of this document are provided for historical
reference. They refer to pre-OS X Macintosh. PortAudio no longer
supports pre-OS X Macintosh. Steinberg does not support ASIO on Mac OS X.
Building PortAudio with ASIO support
------------------------------------
To build PortAudio with ASIO support you need to compile and link with
pa_asio.c, and files from the ASIO SDK (see below), along with the common
PortAudio files from src/common/ and platform specific files from
src/os/win/ (for Win32).
If you are compiling with a non-Microsoft compiler on Windows, also
compile and link with iasiothiscallresolver.cpp (see below for
an explanation).
For some platforms (MingW, Cygwin/MingW), you may simply
be able to type:
./configure --with-host_os=mingw --with-winapi=asio [--with-asiodir=/usr/local/asiosdk2]
make
and life will be good. Make sure you update the above with the correct local
path to the ASIO SDK.
For Microsoft Visual C++ there is an build tutorial here:
http://www.portaudio.com/trac/wiki/TutorialDir/Compile/WindowsASIOMSVC
Obtaining the ASIO SDK
----------------------
In order to build PortAudio with ASIO support, you need to download
the ASIO SDK (version 2.0 or later) from Steinberg. Steinberg makes the ASIO
SDK available to anyone free of charge, however they do not permit its
source code to be distributed.
NOTE: In some cases the ASIO SDK may require patching, see below
for further details.
http://www.steinberg.net/en/company/developer.html
If the above link is broken search Google for:
"download steinberg ASIO SDK"
Building the ASIO SDK on Windows
--------------------------------
To build the ASIO SDK on Windows you need to compile and link with the
following files from the ASIO SDK:
asio_sdk\common\asio.cpp
asio_sdk\host\asiodrivers.cpp
asio_sdk\host\pc\asiolist.cpp
You may also need to adjust your include paths to support inclusion of
header files from the above directories.
The ASIO SDK depends on the following COM API functions:
CoInitialize, CoUninitialize, CoCreateInstance, CLSIDFromString
For compilation with MinGW you will need to link with -lole32, for
Borland compilers link with Import32.lib.
Non-Microsoft (MSVC) Compilers on Windows including Borland and GCC
-------------------------------------------------------------------
Steinberg did not specify a calling convention in the IASIO interface
definition. This causes the Microsoft compiler to use the proprietary
thiscall convention which is not compatible with other compilers, such
as compilers from Borland (BCC and C++Builder) and GNU (gcc).
Steinberg's ASIO SDK will compile but crash on initialization if
compiled with a non-Microsoft compiler on Windows.
PortAudio solves this problem using the iasiothiscallresolver library
which is included in the distribution. When building ASIO support for
non-Microsoft compilers, be sure to compile and link with
iasiothiscallresolver.cpp. Note that iasiothiscallresolver includes
conditional directives which cause it to have no effect if it is
compiled with a Microsoft compiler, or on the Macintosh.
If you use configure and make (see above), this should be handled
automatically for you.
For further information about the IASIO thiscall problem see this page:
http://www.rossbencina.com/code/iasio-thiscall-resolver
Building the ASIO SDK on (Pre-OS X) Macintosh
---------------------------------------------
To build the ASIO SDK on Macintosh you need to compile and link with the
following files from the ASIO SDK:
host/asiodrivers.cpp
host/mac/asioshlib.cpp
host/mac/codefragements.cpp
You may also need to adjust your include paths to support inclusion of
header files from the above directories.
(Pre-OS X) Macintosh ASIO SDK Bug Patch
---------------------------------------
There is a bug in the ASIO SDK that causes the Macintosh version to
often fail during initialization. Below is a patch that you can apply.
In codefragments.cpp replace getFrontProcessDirectory function with
the following one (GetFrontProcess replaced by GetCurrentProcess).
bool CodeFragments::getFrontProcessDirectory(void *specs)
{
FSSpec *fss = (FSSpec *)specs;
ProcessInfoRec pif;
ProcessSerialNumber psn;
memset(&psn,0,(long)sizeof(ProcessSerialNumber));
// if(GetFrontProcess(&psn) == noErr) // wrong !!!
if(GetCurrentProcess(&psn) == noErr) // correct !!!
{
pif.processName = 0;
pif.processAppSpec = fss;
pif.processInfoLength = sizeof(ProcessInfoRec);
if(GetProcessInformation(&psn, &pif) == noErr)
return true;
}
return false;
}
###

View file

@ -0,0 +1,572 @@
/*
IASIOThiscallResolver.cpp see the comments in iasiothiscallresolver.h for
the top level description - this comment describes the technical details of
the implementation.
The latest version of this file is available from:
http://www.audiomulch.com/~rossb/code/calliasio
please email comments to Ross Bencina <rossb@audiomulch.com>
BACKGROUND
The IASIO interface declared in the Steinberg ASIO 2 SDK declares
functions with no explicit calling convention. This causes MSVC++ to default
to using the thiscall convention, which is a proprietary convention not
implemented by some non-microsoft compilers - notably borland BCC,
C++Builder, and gcc. MSVC++ is the defacto standard compiler used by
Steinberg. As a result of this situation, the ASIO sdk will compile with
any compiler, however attempting to execute the compiled code will cause a
crash due to different default calling conventions on non-Microsoft
compilers.
IASIOThiscallResolver solves the problem by providing an adapter class that
delegates to the IASIO interface using the correct calling convention
(thiscall). Due to the lack of support for thiscall in the Borland and GCC
compilers, the calls have been implemented in assembly language.
A number of macros are defined for thiscall function calls with different
numbers of parameters, with and without return values - it may be possible
to modify the format of these macros to make them work with other inline
assemblers.
THISCALL DEFINITION
A number of definitions of the thiscall calling convention are floating
around the internet. The following definition has been validated against
output from the MSVC++ compiler:
For non-vararg functions, thiscall works as follows: the object (this)
pointer is passed in ECX. All arguments are passed on the stack in
right to left order. The return value is placed in EAX. The callee
clears the passed arguments from the stack.
FINDING FUNCTION POINTERS FROM AN IASIO POINTER
The first field of a COM object is a pointer to its vtble. Thus a pointer
to an object implementing the IASIO interface also points to a pointer to
that object's vtbl. The vtble is a table of function pointers for all of
the virtual functions exposed by the implemented interfaces.
If we consider a variable declared as a pointer to IASO:
IASIO *theAsioDriver
theAsioDriver points to:
object implementing IASIO
{
IASIOvtbl *vtbl
other data
}
in other words, theAsioDriver points to a pointer to an IASIOvtbl
vtbl points to a table of function pointers:
IASIOvtbl ( interface IASIO : public IUnknown )
{
(IUnknown functions)
0 virtual HRESULT STDMETHODCALLTYPE (*QueryInterface)(REFIID riid, void **ppv) = 0;
4 virtual ULONG STDMETHODCALLTYPE (*AddRef)() = 0;
8 virtual ULONG STDMETHODCALLTYPE (*Release)() = 0;
(IASIO functions)
12 virtual ASIOBool (*init)(void *sysHandle) = 0;
16 virtual void (*getDriverName)(char *name) = 0;
20 virtual long (*getDriverVersion)() = 0;
24 virtual void (*getErrorMessage)(char *string) = 0;
28 virtual ASIOError (*start)() = 0;
32 virtual ASIOError (*stop)() = 0;
36 virtual ASIOError (*getChannels)(long *numInputChannels, long *numOutputChannels) = 0;
40 virtual ASIOError (*getLatencies)(long *inputLatency, long *outputLatency) = 0;
44 virtual ASIOError (*getBufferSize)(long *minSize, long *maxSize,
long *preferredSize, long *granularity) = 0;
48 virtual ASIOError (*canSampleRate)(ASIOSampleRate sampleRate) = 0;
52 virtual ASIOError (*getSampleRate)(ASIOSampleRate *sampleRate) = 0;
56 virtual ASIOError (*setSampleRate)(ASIOSampleRate sampleRate) = 0;
60 virtual ASIOError (*getClockSources)(ASIOClockSource *clocks, long *numSources) = 0;
64 virtual ASIOError (*setClockSource)(long reference) = 0;
68 virtual ASIOError (*getSamplePosition)(ASIOSamples *sPos, ASIOTimeStamp *tStamp) = 0;
72 virtual ASIOError (*getChannelInfo)(ASIOChannelInfo *info) = 0;
76 virtual ASIOError (*createBuffers)(ASIOBufferInfo *bufferInfos, long numChannels,
long bufferSize, ASIOCallbacks *callbacks) = 0;
80 virtual ASIOError (*disposeBuffers)() = 0;
84 virtual ASIOError (*controlPanel)() = 0;
88 virtual ASIOError (*future)(long selector,void *opt) = 0;
92 virtual ASIOError (*outputReady)() = 0;
};
The numbers in the left column show the byte offset of each function ptr
from the beginning of the vtbl. These numbers are used in the code below
to select different functions.
In order to find the address of a particular function, theAsioDriver
must first be dereferenced to find the value of the vtbl pointer:
mov eax, theAsioDriver
mov edx, [theAsioDriver] // edx now points to vtbl[0]
Then an offset must be added to the vtbl pointer to select a
particular function, for example vtbl+44 points to the slot containing
a pointer to the getBufferSize function.
Finally vtbl+x must be dereferenced to obtain the value of the function
pointer stored in that address:
call [edx+44] // call the function pointed to by
// the value in the getBufferSize field of the vtbl
SEE ALSO
Martin Fay's OpenASIO DLL at http://www.martinfay.com solves the same
problem by providing a new COM interface which wraps IASIO with an
interface that uses portable calling conventions. OpenASIO must be compiled
with MSVC, and requires that you ship the OpenASIO DLL with your
application.
ACKNOWLEDGEMENTS
Ross Bencina: worked out the thiscall details above, wrote the original
Borland asm macros, and a patch for asio.cpp (which is no longer needed).
Thanks to Martin Fay for introducing me to the issues discussed here,
and to Rene G. Ceballos for assisting with asm dumps from MSVC++.
Antti Silvast: converted the original calliasio to work with gcc and NASM
by implementing the asm code in a separate file.
Fraser Adams: modified the original calliasio containing the Borland inline
asm to add inline asm for gcc i.e. Intel syntax for Borland and AT&T syntax
for gcc. This seems a neater approach for gcc than to have a separate .asm
file and it means that we only need one version of the thiscall patch.
Fraser Adams: rewrote the original calliasio patch in the form of the
IASIOThiscallResolver class in order to avoid modifications to files from
the Steinberg SDK, which may have had potential licence issues.
Andrew Baldwin: contributed fixes for compatibility problems with more
recent versions of the gcc assembler.
*/
// We only need IASIOThiscallResolver at all if we are on Win32. For other
// platforms we simply bypass the IASIOThiscallResolver definition to allow us
// to be safely #include'd whatever the platform to keep client code portable
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(_WIN64)
// If microsoft compiler we can call IASIO directly so IASIOThiscallResolver
// is not used.
#if !defined(_MSC_VER)
#include <new>
#include <assert.h>
// We have a mechanism in iasiothiscallresolver.h to ensure that asio.h is
// #include'd before it in client code, we do NOT want to do this test here.
#define iasiothiscallresolver_sourcefile 1
#include "iasiothiscallresolver.h"
#undef iasiothiscallresolver_sourcefile
// iasiothiscallresolver.h redefines ASIOInit for clients, but we don't want
// this macro defined in this translation unit.
#undef ASIOInit
// theAsioDriver is a global pointer to the current IASIO instance which the
// ASIO SDK uses to perform all actions on the IASIO interface. We substitute
// our own forwarding interface into this pointer.
extern IASIO* theAsioDriver;
// The following macros define the inline assembler for BORLAND first then gcc
#if defined(__BCPLUSPLUS__) || defined(__BORLANDC__)
#define CALL_THISCALL_0( resultName, thisPtr, funcOffset )\
void *this_ = (thisPtr); \
__asm { \
mov ecx, this_ ; \
mov eax, [ecx] ; \
call [eax+funcOffset] ; \
mov resultName, eax ; \
}
#define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 )\
void *this_ = (thisPtr); \
__asm { \
mov eax, param1 ; \
push eax ; \
mov ecx, this_ ; \
mov eax, [ecx] ; \
call [eax+funcOffset] ; \
}
#define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 )\
void *this_ = (thisPtr); \
__asm { \
mov eax, param1 ; \
push eax ; \
mov ecx, this_ ; \
mov eax, [ecx] ; \
call [eax+funcOffset] ; \
mov resultName, eax ; \
}
#define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 )\
void *this_ = (thisPtr); \
void *doubleParamPtr_ (&param1); \
__asm { \
mov eax, doubleParamPtr_ ; \
push [eax+4] ; \
push [eax] ; \
mov ecx, this_ ; \
mov eax, [ecx] ; \
call [eax+funcOffset] ; \
mov resultName, eax ; \
}
#define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 )\
void *this_ = (thisPtr); \
__asm { \
mov eax, param2 ; \
push eax ; \
mov eax, param1 ; \
push eax ; \
mov ecx, this_ ; \
mov eax, [ecx] ; \
call [eax+funcOffset] ; \
mov resultName, eax ; \
}
#define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\
void *this_ = (thisPtr); \
__asm { \
mov eax, param4 ; \
push eax ; \
mov eax, param3 ; \
push eax ; \
mov eax, param2 ; \
push eax ; \
mov eax, param1 ; \
push eax ; \
mov ecx, this_ ; \
mov eax, [ecx] ; \
call [eax+funcOffset] ; \
mov resultName, eax ; \
}
#elif defined(__GNUC__)
#define CALL_THISCALL_0( resultName, thisPtr, funcOffset ) \
__asm__ __volatile__ ("movl (%1), %%edx\n\t" \
"call *"#funcOffset"(%%edx)\n\t" \
:"=a"(resultName) /* Output Operands */ \
:"c"(thisPtr) /* Input Operands */ \
: "%edx" /* Clobbered Registers */ \
); \
#define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 ) \
__asm__ __volatile__ ("pushl %0\n\t" \
"movl (%1), %%edx\n\t" \
"call *"#funcOffset"(%%edx)\n\t" \
: /* Output Operands */ \
:"r"(param1), /* Input Operands */ \
"c"(thisPtr) \
: "%edx" /* Clobbered Registers */ \
); \
#define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 ) \
__asm__ __volatile__ ("pushl %1\n\t" \
"movl (%2), %%edx\n\t" \
"call *"#funcOffset"(%%edx)\n\t" \
:"=a"(resultName) /* Output Operands */ \
:"r"(param1), /* Input Operands */ \
"c"(thisPtr) \
: "%edx" /* Clobbered Registers */ \
); \
#define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 ) \
do { \
double param1f64 = param1; /* Cast explicitly to double */ \
double *param1f64Ptr = &param1f64; /* Make pointer to address */ \
__asm__ __volatile__ ("pushl 4(%1)\n\t" \
"pushl (%1)\n\t" \
"movl (%2), %%edx\n\t" \
"call *"#funcOffset"(%%edx);\n\t" \
: "=a"(resultName) /* Output Operands */ \
: "r"(param1f64Ptr), /* Input Operands */ \
"c"(thisPtr), \
"m"(*param1f64Ptr) /* Using address */ \
: "%edx" /* Clobbered Registers */ \
); \
} while (0); \
#define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 ) \
__asm__ __volatile__ ("pushl %1\n\t" \
"pushl %2\n\t" \
"movl (%3), %%edx\n\t" \
"call *"#funcOffset"(%%edx)\n\t" \
:"=a"(resultName) /* Output Operands */ \
:"r"(param2), /* Input Operands */ \
"r"(param1), \
"c"(thisPtr) \
: "%edx" /* Clobbered Registers */ \
); \
#define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\
__asm__ __volatile__ ("pushl %1\n\t" \
"pushl %2\n\t" \
"pushl %3\n\t" \
"pushl %4\n\t" \
"movl (%5), %%edx\n\t" \
"call *"#funcOffset"(%%edx)\n\t" \
:"=a"(resultName) /* Output Operands */ \
:"r"(param4), /* Input Operands */ \
"r"(param3), \
"r"(param2), \
"r"(param1), \
"c"(thisPtr) \
: "%edx" /* Clobbered Registers */ \
); \
#endif
// Our static singleton instance.
IASIOThiscallResolver IASIOThiscallResolver::instance;
// Constructor called to initialize static Singleton instance above. Note that
// it is important not to clear that_ incase it has already been set by the call
// to placement new in ASIOInit().
IASIOThiscallResolver::IASIOThiscallResolver()
{
}
// Constructor called from ASIOInit() below
IASIOThiscallResolver::IASIOThiscallResolver(IASIO* that)
: that_( that )
{
}
// Implement IUnknown methods as assert(false). IASIOThiscallResolver is not
// really a COM object, just a wrapper which will work with the ASIO SDK.
// If you wanted to use ASIO without the SDK you might want to implement COM
// aggregation in these methods.
HRESULT STDMETHODCALLTYPE IASIOThiscallResolver::QueryInterface(REFIID riid, void **ppv)
{
(void)riid; // suppress unused variable warning
assert( false ); // this function should never be called by the ASIO SDK.
*ppv = NULL;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE IASIOThiscallResolver::AddRef()
{
assert( false ); // this function should never be called by the ASIO SDK.
return 1;
}
ULONG STDMETHODCALLTYPE IASIOThiscallResolver::Release()
{
assert( false ); // this function should never be called by the ASIO SDK.
return 1;
}
// Implement the IASIO interface methods by performing the vptr manipulation
// described above then delegating to the real implementation.
ASIOBool IASIOThiscallResolver::init(void *sysHandle)
{
ASIOBool result;
CALL_THISCALL_1( result, that_, 12, sysHandle );
return result;
}
void IASIOThiscallResolver::getDriverName(char *name)
{
CALL_VOID_THISCALL_1( that_, 16, name );
}
long IASIOThiscallResolver::getDriverVersion()
{
ASIOBool result;
CALL_THISCALL_0( result, that_, 20 );
return result;
}
void IASIOThiscallResolver::getErrorMessage(char *string)
{
CALL_VOID_THISCALL_1( that_, 24, string );
}
ASIOError IASIOThiscallResolver::start()
{
ASIOBool result;
CALL_THISCALL_0( result, that_, 28 );
return result;
}
ASIOError IASIOThiscallResolver::stop()
{
ASIOBool result;
CALL_THISCALL_0( result, that_, 32 );
return result;
}
ASIOError IASIOThiscallResolver::getChannels(long *numInputChannels, long *numOutputChannels)
{
ASIOBool result;
CALL_THISCALL_2( result, that_, 36, numInputChannels, numOutputChannels );
return result;
}
ASIOError IASIOThiscallResolver::getLatencies(long *inputLatency, long *outputLatency)
{
ASIOBool result;
CALL_THISCALL_2( result, that_, 40, inputLatency, outputLatency );
return result;
}
ASIOError IASIOThiscallResolver::getBufferSize(long *minSize, long *maxSize,
long *preferredSize, long *granularity)
{
ASIOBool result;
CALL_THISCALL_4( result, that_, 44, minSize, maxSize, preferredSize, granularity );
return result;
}
ASIOError IASIOThiscallResolver::canSampleRate(ASIOSampleRate sampleRate)
{
ASIOBool result;
CALL_THISCALL_1_DOUBLE( result, that_, 48, sampleRate );
return result;
}
ASIOError IASIOThiscallResolver::getSampleRate(ASIOSampleRate *sampleRate)
{
ASIOBool result;
CALL_THISCALL_1( result, that_, 52, sampleRate );
return result;
}
ASIOError IASIOThiscallResolver::setSampleRate(ASIOSampleRate sampleRate)
{
ASIOBool result;
CALL_THISCALL_1_DOUBLE( result, that_, 56, sampleRate );
return result;
}
ASIOError IASIOThiscallResolver::getClockSources(ASIOClockSource *clocks, long *numSources)
{
ASIOBool result;
CALL_THISCALL_2( result, that_, 60, clocks, numSources );
return result;
}
ASIOError IASIOThiscallResolver::setClockSource(long reference)
{
ASIOBool result;
CALL_THISCALL_1( result, that_, 64, reference );
return result;
}
ASIOError IASIOThiscallResolver::getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp)
{
ASIOBool result;
CALL_THISCALL_2( result, that_, 68, sPos, tStamp );
return result;
}
ASIOError IASIOThiscallResolver::getChannelInfo(ASIOChannelInfo *info)
{
ASIOBool result;
CALL_THISCALL_1( result, that_, 72, info );
return result;
}
ASIOError IASIOThiscallResolver::createBuffers(ASIOBufferInfo *bufferInfos,
long numChannels, long bufferSize, ASIOCallbacks *callbacks)
{
ASIOBool result;
CALL_THISCALL_4( result, that_, 76, bufferInfos, numChannels, bufferSize, callbacks );
return result;
}
ASIOError IASIOThiscallResolver::disposeBuffers()
{
ASIOBool result;
CALL_THISCALL_0( result, that_, 80 );
return result;
}
ASIOError IASIOThiscallResolver::controlPanel()
{
ASIOBool result;
CALL_THISCALL_0( result, that_, 84 );
return result;
}
ASIOError IASIOThiscallResolver::future(long selector,void *opt)
{
ASIOBool result;
CALL_THISCALL_2( result, that_, 88, selector, opt );
return result;
}
ASIOError IASIOThiscallResolver::outputReady()
{
ASIOBool result;
CALL_THISCALL_0( result, that_, 92 );
return result;
}
// Implement our substitute ASIOInit() method
ASIOError IASIOThiscallResolver::ASIOInit(ASIODriverInfo *info)
{
// To ensure that our instance's vptr is correctly constructed, even if
// ASIOInit is called prior to main(), we explicitly call its constructor
// (potentially over the top of an existing instance). Note that this is
// pretty ugly, and is only safe because IASIOThiscallResolver has no
// destructor and contains no objects with destructors.
new((void*)&instance) IASIOThiscallResolver( theAsioDriver );
// Interpose between ASIO client code and the real driver.
theAsioDriver = &instance;
// Note that we never need to switch theAsioDriver back to point to the
// real driver because theAsioDriver is reset to zero in ASIOExit().
// Delegate to the real ASIOInit
return ::ASIOInit(info);
}
#endif /* !defined(_MSC_VER) */
#endif /* Win32 */

View file

@ -0,0 +1,197 @@
// ****************************************************************************
// File: IASIOThiscallResolver.h
// Description: The IASIOThiscallResolver class implements the IASIO
// interface and acts as a proxy to the real IASIO interface by
// calling through its vptr table using the thiscall calling
// convention. To put it another way, we interpose
// IASIOThiscallResolver between ASIO SDK code and the driver.
// This is necessary because most non-Microsoft compilers don't
// implement the thiscall calling convention used by IASIO.
//
// iasiothiscallresolver.cpp contains the background of this
// problem plus a technical description of the vptr
// manipulations.
//
// In order to use this mechanism one simply has to add
// iasiothiscallresolver.cpp to the list of files to compile
// and #include <iasiothiscallresolver.h>
//
// Note that this #include must come after the other ASIO SDK
// #includes, for example:
//
// #include <windows.h>
// #include <asiosys.h>
// #include <asio.h>
// #include <asiodrivers.h>
// #include <iasiothiscallresolver.h>
//
// Actually the important thing is to #include
// <iasiothiscallresolver.h> after <asio.h>. We have
// incorporated a test to enforce this ordering.
//
// The code transparently takes care of the interposition by
// using macro substitution to intercept calls to ASIOInit()
// and ASIOExit(). We save the original ASIO global
// "theAsioDriver" in our "that" variable, and then set
// "theAsioDriver" to equal our IASIOThiscallResolver instance.
//
// Whilst this method of resolving the thiscall problem requires
// the addition of #include <iasiothiscallresolver.h> to client
// code it has the advantage that it does not break the terms
// of the ASIO licence by publishing it. We are NOT modifying
// any Steinberg code here, we are merely implementing the IASIO
// interface in the same way that we would need to do if we
// wished to provide an open source ASIO driver.
//
// For compilation with MinGW -lole32 needs to be added to the
// linker options. For BORLAND, linking with Import32.lib is
// sufficient.
//
// The dependencies are with: CoInitialize, CoUninitialize,
// CoCreateInstance, CLSIDFromString - used by asiolist.cpp
// and are required on Windows whether ThiscallResolver is used
// or not.
//
// Searching for the above strings in the root library path
// of your compiler should enable the correct libraries to be
// identified if they aren't immediately obvious.
//
// Note that the current implementation of IASIOThiscallResolver
// is not COM compliant - it does not correctly implement the
// IUnknown interface. Implementing it is not necessary because
// it is not called by parts of the ASIO SDK which call through
// theAsioDriver ptr. The IUnknown methods are implemented as
// assert(false) to ensure that the code fails if they are
// ever called.
// Restrictions: None. Public Domain & Open Source distribute freely
// You may use IASIOThiscallResolver commercially as well as
// privately.
// You the user assume the responsibility for the use of the
// files, binary or text, and there is no guarantee or warranty,
// expressed or implied, including but not limited to the
// implied warranties of merchantability and fitness for a
// particular purpose. You assume all responsibility and agree
// to hold no entity, copyright holder or distributors liable
// for any loss of data or inaccurate representations of data
// as a result of using IASIOThiscallResolver.
// Version: 1.4 Added separate macro CALL_THISCALL_1_DOUBLE from
// Andrew Baldwin, and volatile for whole gcc asm blocks,
// both for compatibility with newer gcc versions. Cleaned up
// Borland asm to use one less register.
// 1.3 Switched to including assert.h for better compatibility.
// Wrapped entire .h and .cpp contents with a check for
// _MSC_VER to provide better compatibility with MS compilers.
// Changed Singleton implementation to use static instance
// instead of freestore allocated instance. Removed ASIOExit
// macro as it is no longer needed.
// 1.2 Removed semicolons from ASIOInit and ASIOExit macros to
// allow them to be embedded in expressions (if statements).
// Cleaned up some comments. Removed combase.c dependency (it
// doesn't compile with BCB anyway) by stubbing IUnknown.
// 1.1 Incorporated comments from Ross Bencina including things
// such as changing name from ThiscallResolver to
// IASIOThiscallResolver, tidying up the constructor, fixing
// a bug in IASIOThiscallResolver::ASIOExit() and improving
// portability through the use of conditional compilation
// 1.0 Initial working version.
// Created: 6/09/2003
// Authors: Fraser Adams
// Ross Bencina
// Rene G. Ceballos
// Martin Fay
// Antti Silvast
// Andrew Baldwin
//
// ****************************************************************************
#ifndef included_iasiothiscallresolver_h
#define included_iasiothiscallresolver_h
// We only need IASIOThiscallResolver at all if we are on Win32. For other
// platforms we simply bypass the IASIOThiscallResolver definition to allow us
// to be safely #include'd whatever the platform to keep client code portable
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(_WIN64)
// If microsoft compiler we can call IASIO directly so IASIOThiscallResolver
// is not used.
#if !defined(_MSC_VER)
// The following is in order to ensure that this header is only included after
// the other ASIO headers (except for the case of iasiothiscallresolver.cpp).
// We need to do this because IASIOThiscallResolver works by eclipsing the
// original definition of ASIOInit() with a macro (see below).
#if !defined(iasiothiscallresolver_sourcefile)
#if !defined(__ASIO_H)
#error iasiothiscallresolver.h must be included AFTER asio.h
#endif
#endif
#include <windows.h>
#include <asiodrvr.h> /* From ASIO SDK */
class IASIOThiscallResolver : public IASIO {
private:
IASIO* that_; // Points to the real IASIO
static IASIOThiscallResolver instance; // Singleton instance
// Constructors - declared private so construction is limited to
// our Singleton instance
IASIOThiscallResolver();
IASIOThiscallResolver(IASIO* that);
public:
// Methods from the IUnknown interface. We don't fully implement IUnknown
// because the ASIO SDK never calls these methods through theAsioDriver ptr.
// These methods are implemented as assert(false).
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv);
virtual ULONG STDMETHODCALLTYPE AddRef();
virtual ULONG STDMETHODCALLTYPE Release();
// Methods from the IASIO interface, implemented as forwarning calls to that.
virtual ASIOBool init(void *sysHandle);
virtual void getDriverName(char *name);
virtual long getDriverVersion();
virtual void getErrorMessage(char *string);
virtual ASIOError start();
virtual ASIOError stop();
virtual ASIOError getChannels(long *numInputChannels, long *numOutputChannels);
virtual ASIOError getLatencies(long *inputLatency, long *outputLatency);
virtual ASIOError getBufferSize(long *minSize, long *maxSize, long *preferredSize, long *granularity);
virtual ASIOError canSampleRate(ASIOSampleRate sampleRate);
virtual ASIOError getSampleRate(ASIOSampleRate *sampleRate);
virtual ASIOError setSampleRate(ASIOSampleRate sampleRate);
virtual ASIOError getClockSources(ASIOClockSource *clocks, long *numSources);
virtual ASIOError setClockSource(long reference);
virtual ASIOError getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp);
virtual ASIOError getChannelInfo(ASIOChannelInfo *info);
virtual ASIOError createBuffers(ASIOBufferInfo *bufferInfos, long numChannels, long bufferSize, ASIOCallbacks *callbacks);
virtual ASIOError disposeBuffers();
virtual ASIOError controlPanel();
virtual ASIOError future(long selector,void *opt);
virtual ASIOError outputReady();
// Class method, see ASIOInit() macro below.
static ASIOError ASIOInit(ASIODriverInfo *info); // Delegates to ::ASIOInit
};
// Replace calls to ASIOInit with our interposing version.
// This macro enables us to perform thiscall resolution simply by #including
// <iasiothiscallresolver.h> after the asio #includes (this file _must_ be
// included _after_ the asio #includes)
#define ASIOInit(name) IASIOThiscallResolver::ASIOInit((name))
#endif /* !defined(_MSC_VER) */
#endif /* Win32 */
#endif /* included_iasiothiscallresolver_h */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,196 @@
Notes on status of CoreAudio Implementation of PortAudio
Document Last Updated December 9, 2005
There are currently two implementations of PortAudio for Mac Core Audio.
The original is in pa_mac_core_old.c, and the newer, default implementation
is in pa_mac_core.c.
Only pa_mac_core.c is currently developed and supported as it uses apple's
current core audio technology. To select use the old implementation, replace
pa_mac_core.c with pa_mac_core_old.c (eg. "cp pa_mac_core_auhal.c
pa_mac_core.c"), then run configure and make as usual.
-------------------------------------------
Notes on Newer/Default AUHAL implementation:
by Bjorn Roche
Last Updated December 9, 2005
Principle of Operation:
This implementation uses AUHAL for audio I/O. To some extent, it also
operates at the "HAL" Layer, though this behavior can be limited by
platform specific flags (see pa_mac_core.h for details). The default
settings should be reasonable: they don't change the SR of the device and
don't cause interruptions if other devices are using the device.
Major Software Elements Used: Apple's HAL AUs provide output SR
conversion transparently, however, only on output, so this
implementation uses AudioConverters to convert the sample rate on input.
A PortAudio ring buffer is used to buffer input when sample rate
conversion is required or when separate audio units are used for duplex
IO. Finally, a PortAudio buffer processor is used to convert formats and
provide additional buffers if needed. Internally, interleaved floating
point data streams are used exclusively - the audio unit converts from
the audio hardware's native format to interleaved float PCM and
PortAudio's Buffer processor is used for conversion to user formats.
Simplex Input: Simplex input uses a single callback. If sample rate
conversion is required, a ring buffer and AudioConverter are used as
well.
Simplex output: Simplex output uses a single callback. No ring buffer or
audio converter is used because AUHAL does its own output SR conversion.
Duplex, one device (no SR conversion): When one device is used, a single
callback is used. This achieves very low latency.
Duplex, separate devices or SR conversion: When SR conversion is
required, data must be buffered before it is converted and data is not
always available at the same times on input and output, so SR conversion
requires the same treatment as separate devices. The input callback
reads data and puts it in the ring buffer. The output callback reads the
data off the ring buffer, into an audio converter and finally to the
buffer processor.
Platform Specific Options:
By using the flags in pa_mac_core.h, the user may specify several options.
For example, the user can specify the sample-rate conversion quality, and
the extent to which PA will attempt to "play nice" and to what extent it
will interrupt other apps to improve performance. For example, if 44100 Hz
sample rate is requested but the device is set at 48000 Hz, PA can either
change the device for optimal playback ("Pro" mode), which may interrupt
other programs playing back audio, or simple use a sample-rate conversion,
which allows for friendlier sharing of the device ("Play Nice" mode).
Additionally, the user may define a "channel mapping" by calling
paSetupMacCoreChannelMap() on their stream info structure before opening
the stream with it. See below for creating a channel map.
Known issues:
- Buffering: No buffering beyond that provided by core audio is provided
except where absolutely needed for the implementation to work. This may cause
issues with large framesPerBuffer settings and it also means that no additional
latency will be provided even if a large latency setting is selected.
- Latency: Latency settings are generally ignored. They may be used as a
hint for buffer size in paHostFramesPerBufferUnspecified, or the value may
be used in cases where additional buffering is needed, such as doing input and
output on separate devices. Latency settings are always automatically bound
to "safe" values, however, so setting extreme values here should not be
an issue.
- Buffer Size: paHostFramesPerBufferUnspecified and specific host buffer sizes
are supported. paHostFramesPerBufferUnspecified works best in "pro" mode,
where the buffer size and sample rate of the audio device is most likely
to match the expected values. In the case of paHostFramesPerBuffer, an
appropriate framesPerBuffer value will be used that guarantees minimum
requested latency if that's possible.
- Timing info. It reports on stream time, but I'm probably doing something
wrong since patest_sine_time often reports negative latency numbers. Also,
there are currently issues with some devices whehn plugging/unplugging
devices.
- xrun detection: The only xrun detection performed is when reading
and writing the ring buffer. There is probably more that can be done.
- abort/stop issues: stopping a stream is always a complete operation,
but latency should be low enough to make the lack of a separate abort
unnecessary. Apple clarifies its AudioOutputUnitStop() call here:
http://lists.apple.com/archives/coreaudio-api/2005/Dec/msg00055.html
- blocking interface: should work fine.
- multichannel: It has been tested successfully on multichannel hardware
from MOTU: traveler and 896HD. Also Presonus firepod and others. It is
believed to work with all Core Audio devices, including virtual devices
such as soundflower.
- sample rate conversion quality: By default, SR conversion is the maximum
available. This can be tweaked using flags pa_mac_core.h. Note that the AU
render quyality property is used to set the sample rate conversion quality
as "documented" here:
http://lists.apple.com/archives/coreaudio-api/2004/Jan/msg00141.html
- x86/Universal Binary: Universal binaries can be build.
Creating a channel map:
How to create the map array - Text taken From AUHAL.rtfd :
[3] Channel Maps
Clients can tell the AUHAL units which channels of the device they are interested in. For example, the client may be processing stereo data, but outputting to a six-channel device. This is done by using the kAudioOutputUnitProperty_ChannelMap property. To use this property:
For Output:
Create an array of SInt32 that is the size of the number of channels of the device (Get the Format of the AUHAL's output Element == 0)
Initialize each of the array's values to -1 (-1 indicates that that channel is NOT to be presented in the conversion.)
Next, for each channel of your app's output, set:
channelMapArray[deviceOutputChannel] = desiredAppOutputChannel.
For example: we have a 6 channel output device and our application has a stereo source it wants to provide to the device. Suppose we want that stereo source to go to the 3rd and 4th channels of the device. The channel map would look like this: { -1, -1, 0, 1, -1, -1 }
Where the formats are:
Input Element == 0: 2 channels (- client format - settable)
Output Element == 0: 6 channels (- device format - NOT settable)
So channel 2 (zero-based) of the device will take the first channel of output and channel 3 will take the second channel of output. (This translates to the 3rd and 4th plugs of the 6 output plugs of the device of course!)
For Input:
Create an array of SInt32 that is the size of the number of channels of the format you require for input. Get (or Set in this case as needed) the AUHAL's output Element == 1.
Next, for each channel of input you require, set:
channelMapArray[desiredAppInputChannel] = deviceOutputChannel;
For example: we have a 6 channel input device from which we wish to receive stereo input from the 3rd and 4th channels. The channel map looks like this: { 2, 3 }
Where the formats are:
Input Element == 0: 2 channels (- device format - NOT settable)
Output Element == 0: 6 channels (- client format - settable)
----------------------------------------
Notes on Original implementation:
by Phil Burk and Darren Gibbs
Last updated March 20, 2002
WHAT WORKS
Output with very low latency, <10 msec.
Half duplex input or output.
Full duplex on the same CoreAudio device.
The paFLoat32, paInt16, paInt8, paUInt8 sample formats.
Pa_GetCPULoad()
Pa_StreamTime()
KNOWN BUGS OR LIMITATIONS
We do not yet support simultaneous input and output on different
devices. Note that some CoreAudio devices like the Roland UH30 look
like one device but are actually two different CoreAudio devices. The
Built-In audio is typically one CoreAudio device.
Mono doesn't work.
DEVICE MAPPING
CoreAudio devices can support both input and output. But the sample
rates supported may be different. So we have map one or two PortAudio
device to each CoreAudio device depending on whether it supports
input, output or both.
When we query devices, we first get a list of CoreAudio devices. Then
we scan the list and add a PortAudio device for each CoreAudio device
that supports input. Then we make a scan for output devices.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,638 @@
/*
* Implementation of the PortAudio API for Apple AUHAL
*
* PortAudio Portable Real-Time Audio Library
* Latest Version at: http://www.portaudio.com
*
* Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
* Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
*
* Dominic's code was based on code by Phil Burk, Darren Gibbs,
* Gord Peters, Stephane Letz, and Greg Pfiel.
*
* The following people also deserve acknowledgements:
*
* Olivier Tristan for feedback and testing
* Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
* interface.
*
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/**
@file
@ingroup hostapi_src
This file contains the implementation
required for blocking I/O. It is separated from pa_mac_core.c simply to ease
development.
*/
#include "pa_mac_core_blocking.h"
#include "pa_mac_core_internal.h"
#include <assert.h>
#ifdef MOSX_USE_NON_ATOMIC_FLAG_BITS
# define OSAtomicOr32( a, b ) ( (*(b)) |= (a) )
# define OSAtomicAnd32( a, b ) ( (*(b)) &= (a) )
#else
# include <libkern/OSAtomic.h>
#endif
/*
* This function determines the size of a particular sample format.
* if the format is not recognized, this returns zero.
*/
static size_t computeSampleSizeFromFormat( PaSampleFormat format )
{
switch( format & (~paNonInterleaved) ) {
case paFloat32: return 4;
case paInt32: return 4;
case paInt24: return 3;
case paInt16: return 2;
case paInt8:
case paUInt8: return 1;
default: return 0;
}
}
/*
* Same as computeSampleSizeFromFormat, except that if
* the size is not a power of two, it returns the next power of two up
*/
static size_t computeSampleSizeFromFormatPow2( PaSampleFormat format )
{
switch( format & (~paNonInterleaved) ) {
case paFloat32: return 4;
case paInt32: return 4;
case paInt24: return 4;
case paInt16: return 2;
case paInt8:
case paUInt8: return 1;
default: return 0;
}
}
/*
* Functions for initializing, resetting, and destroying BLIO structures.
*
*/
/**
* This should be called with the relevant info when initializing a stream for callback.
*
* @param ringBufferSizeInFrames must be a power of 2
*/
PaError initializeBlioRingBuffers(
PaMacBlio *blio,
PaSampleFormat inputSampleFormat,
PaSampleFormat outputSampleFormat,
long ringBufferSizeInFrames,
int inChan,
int outChan )
{
void *data;
int result;
OSStatus err;
/* zeroify things */
bzero( blio, sizeof( PaMacBlio ) );
/* this is redundant, but the buffers are used to check
if the buffers have been initialized, so we do it explicitly. */
blio->inputRingBuffer.buffer = NULL;
blio->outputRingBuffer.buffer = NULL;
/* initialize simple data */
blio->ringBufferFrames = ringBufferSizeInFrames;
blio->inputSampleFormat = inputSampleFormat;
blio->inputSampleSizeActual = computeSampleSizeFromFormat(inputSampleFormat);
blio->inputSampleSizePow2 = computeSampleSizeFromFormatPow2(inputSampleFormat); // FIXME: WHY?
blio->outputSampleFormat = outputSampleFormat;
blio->outputSampleSizeActual = computeSampleSizeFromFormat(outputSampleFormat);
blio->outputSampleSizePow2 = computeSampleSizeFromFormatPow2(outputSampleFormat);
blio->inChan = inChan;
blio->outChan = outChan;
blio->statusFlags = 0;
blio->errors = paNoError;
#ifdef PA_MAC_BLIO_MUTEX
blio->isInputEmpty = false;
blio->isOutputFull = false;
#endif
/* setup ring buffers */
#ifdef PA_MAC_BLIO_MUTEX
result = PaMacCore_SetUnixError( pthread_mutex_init(&(blio->inputMutex),NULL), 0 );
if( result )
goto error;
result = UNIX_ERR( pthread_cond_init( &(blio->inputCond), NULL ) );
if( result )
goto error;
result = UNIX_ERR( pthread_mutex_init(&(blio->outputMutex),NULL) );
if( result )
goto error;
result = UNIX_ERR( pthread_cond_init( &(blio->outputCond), NULL ) );
#endif
if( inChan ) {
data = calloc( ringBufferSizeInFrames, blio->inputSampleSizePow2 * inChan );
if( !data )
{
result = paInsufficientMemory;
goto error;
}
err = PaUtil_InitializeRingBuffer(
&blio->inputRingBuffer,
blio->inputSampleSizePow2 * inChan,
ringBufferSizeInFrames,
data );
assert( !err );
}
if( outChan ) {
data = calloc( ringBufferSizeInFrames, blio->outputSampleSizePow2 * outChan );
if( !data )
{
result = paInsufficientMemory;
goto error;
}
err = PaUtil_InitializeRingBuffer(
&blio->outputRingBuffer,
blio->outputSampleSizePow2 * outChan,
ringBufferSizeInFrames,
data );
assert( !err );
}
result = resetBlioRingBuffers( blio );
if( result )
goto error;
return 0;
error:
destroyBlioRingBuffers( blio );
return result;
}
#ifdef PA_MAC_BLIO_MUTEX
PaError blioSetIsInputEmpty( PaMacBlio *blio, bool isEmpty )
{
PaError result = paNoError;
if( isEmpty == blio->isInputEmpty )
goto done;
/* we need to update the value. Here's what we do:
* - Lock the mutex, so no one else can write.
* - update the value.
* - unlock.
* - broadcast to all listeners.
*/
result = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) );
if( result )
goto done;
blio->isInputEmpty = isEmpty;
result = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) );
if( result )
goto done;
result = UNIX_ERR( pthread_cond_broadcast( &blio->inputCond ) );
if( result )
goto done;
done:
return result;
}
PaError blioSetIsOutputFull( PaMacBlio *blio, bool isFull )
{
PaError result = paNoError;
if( isFull == blio->isOutputFull )
goto done;
/* we need to update the value. Here's what we do:
* - Lock the mutex, so no one else can write.
* - update the value.
* - unlock.
* - broadcast to all listeners.
*/
result = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) );
if( result )
goto done;
blio->isOutputFull = isFull;
result = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) );
if( result )
goto done;
result = UNIX_ERR( pthread_cond_broadcast( &blio->outputCond ) );
if( result )
goto done;
done:
return result;
}
#endif
/* This should be called after stopping or aborting the stream, so that on next
start, the buffers will be ready. */
PaError resetBlioRingBuffers( PaMacBlio *blio )
{
#ifdef PA_MAC__BLIO_MUTEX
int result;
#endif
blio->statusFlags = 0;
if( blio->outputRingBuffer.buffer ) {
PaUtil_FlushRingBuffer( &blio->outputRingBuffer );
/* Fill the buffer with zeros. */
bzero( blio->outputRingBuffer.buffer,
blio->outputRingBuffer.bufferSize * blio->outputRingBuffer.elementSizeBytes );
PaUtil_AdvanceRingBufferWriteIndex( &blio->outputRingBuffer, blio->ringBufferFrames );
/* Update isOutputFull. */
#ifdef PA_MAC__BLIO_MUTEX
result = blioSetIsOutputFull( blio, toAdvance == blio->outputRingBuffer.bufferSize );
if( result )
goto error;
#endif
/*
printf( "------%d\n" , blio->outChan );
printf( "------%d\n" , blio->outputSampleSize );
*/
}
if( blio->inputRingBuffer.buffer ) {
PaUtil_FlushRingBuffer( &blio->inputRingBuffer );
bzero( blio->inputRingBuffer.buffer,
blio->inputRingBuffer.bufferSize * blio->inputRingBuffer.elementSizeBytes );
/* Update isInputEmpty. */
#ifdef PA_MAC__BLIO_MUTEX
result = blioSetIsInputEmpty( blio, true );
if( result )
goto error;
#endif
}
return paNoError;
#ifdef PA_MAC__BLIO_MUTEX
error:
return result;
#endif
}
/*This should be called when you are done with the blio. It can safely be called
multiple times if there are no exceptions. */
PaError destroyBlioRingBuffers( PaMacBlio *blio )
{
PaError result = paNoError;
if( blio->inputRingBuffer.buffer ) {
free( blio->inputRingBuffer.buffer );
#ifdef PA_MAC__BLIO_MUTEX
result = UNIX_ERR( pthread_mutex_destroy( & blio->inputMutex ) );
if( result ) return result;
result = UNIX_ERR( pthread_cond_destroy( & blio->inputCond ) );
if( result ) return result;
#endif
}
blio->inputRingBuffer.buffer = NULL;
if( blio->outputRingBuffer.buffer ) {
free( blio->outputRingBuffer.buffer );
#ifdef PA_MAC__BLIO_MUTEX
result = UNIX_ERR( pthread_mutex_destroy( & blio->outputMutex ) );
if( result ) return result;
result = UNIX_ERR( pthread_cond_destroy( & blio->outputCond ) );
if( result ) return result;
#endif
}
blio->outputRingBuffer.buffer = NULL;
return result;
}
/*
* this is the BlioCallback function. It expects to receive a PaMacBlio Object
* pointer as userData.
*
*/
int BlioCallback( const void *input, void *output, unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
PaMacBlio *blio = (PaMacBlio*)userData;
ring_buffer_size_t framesAvailable;
ring_buffer_size_t framesToTransfer;
ring_buffer_size_t framesTransferred;
/* set flags returned by OS: */
OSAtomicOr32( statusFlags, &blio->statusFlags ) ;
/* --- Handle Input Buffer --- */
if( blio->inChan ) {
framesAvailable = PaUtil_GetRingBufferWriteAvailable( &blio->inputRingBuffer );
/* check for underflow */
if( framesAvailable < frameCount )
{
OSAtomicOr32( paInputOverflow, &blio->statusFlags );
framesToTransfer = framesAvailable;
}
else
{
framesToTransfer = (ring_buffer_size_t)frameCount;
}
/* Copy the data from the audio input to the application ring buffer. */
/*printf( "reading %d\n", toRead );*/
framesTransferred = PaUtil_WriteRingBuffer( &blio->inputRingBuffer, input, framesToTransfer );
assert( framesToTransfer == framesTransferred );
#ifdef PA_MAC__BLIO_MUTEX
/* Priority inversion. See notes below. */
blioSetIsInputEmpty( blio, false );
#endif
}
/* --- Handle Output Buffer --- */
if( blio->outChan ) {
framesAvailable = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
/* check for underflow */
if( framesAvailable < frameCount )
{
/* zero out the end of the output buffer that we do not have data for */
framesToTransfer = framesAvailable;
size_t bytesPerFrame = blio->outputSampleSizeActual * blio->outChan;
size_t offsetInBytes = framesToTransfer * bytesPerFrame;
size_t countInBytes = (frameCount - framesToTransfer) * bytesPerFrame;
bzero( ((char *)output) + offsetInBytes, countInBytes );
OSAtomicOr32( paOutputUnderflow, &blio->statusFlags );
framesToTransfer = framesAvailable;
}
else
{
framesToTransfer = (ring_buffer_size_t)frameCount;
}
/* copy the data */
/*printf( "writing %d\n", toWrite );*/
framesTransferred = PaUtil_ReadRingBuffer( &blio->outputRingBuffer, output, framesToTransfer );
assert( framesToTransfer == framesTransferred );
#ifdef PA_MAC__BLIO_MUTEX
/* We have a priority inversion here. However, we will only have to
wait if this was true and is now false, which means we've got
some room in the buffer.
Hopefully problems will be minimized. */
blioSetIsOutputFull( blio, false );
#endif
}
return paContinue;
}
PaError ReadStream( PaStream* stream,
void *buffer,
unsigned long framesRequested )
{
PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
char *cbuf = (char *) buffer;
PaError ret = paNoError;
VVDBUG(("ReadStream()\n"));
while( framesRequested > 0 ) {
ring_buffer_size_t framesAvailable;
ring_buffer_size_t framesToTransfer;
ring_buffer_size_t framesTransferred;
do {
framesAvailable = PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer );
/*
printf( "Read Buffer is %%%g full: %ld of %ld.\n",
100 * (float)avail / (float) blio->inputRingBuffer.bufferSize,
framesAvailable, blio->inputRingBuffer.bufferSize );
*/
if( framesAvailable == 0 ) {
#ifdef PA_MAC_BLIO_MUTEX
/**block when empty*/
ret = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) );
if( ret )
return ret;
while( blio->isInputEmpty ) {
ret = UNIX_ERR( pthread_cond_wait( &blio->inputCond, &blio->inputMutex ) );
if( ret )
return ret;
}
ret = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) );
if( ret )
return ret;
#else
Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );
#endif
}
} while( framesAvailable == 0 );
framesToTransfer = (ring_buffer_size_t) MIN( framesAvailable, framesRequested );
framesTransferred = PaUtil_ReadRingBuffer( &blio->inputRingBuffer, (void *)cbuf, framesToTransfer );
cbuf += framesTransferred * blio->inputSampleSizeActual * blio->inChan;
framesRequested -= framesTransferred;
if( framesToTransfer == framesAvailable ) {
#ifdef PA_MAC_BLIO_MUTEX
/* we just emptied the buffer, so we need to mark it as empty. */
ret = blioSetIsInputEmpty( blio, true );
if( ret )
return ret;
/* of course, in the meantime, the callback may have put some sats
in, so
so check for that, too, to avoid a race condition. */
/* FIXME - this does not seem to fix any race condition. */
if( PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer ) ) {
blioSetIsInputEmpty( blio, false );
/* FIXME - why check? ret has not been set? */
if( ret )
return ret;
}
#endif
}
}
/* Report either paNoError or paInputOverflowed. */
/* may also want to report other errors, but this is non-standard. */
/* FIXME should not clobber ret, use if(blio->statusFlags & paInputOverflow) */
ret = blio->statusFlags & paInputOverflow;
/* report underflow only once: */
if( ret ) {
OSAtomicAnd32( (uint32_t)(~paInputOverflow), &blio->statusFlags );
ret = paInputOverflowed;
}
return ret;
}
PaError WriteStream( PaStream* stream,
const void *buffer,
unsigned long framesRequested )
{
PaMacCoreStream *macStream = (PaMacCoreStream*)stream;
PaMacBlio *blio = &macStream->blio;
char *cbuf = (char *) buffer;
PaError ret = paNoError;
VVDBUG(("WriteStream()\n"));
while( framesRequested > 0 && macStream->state != STOPPING ) {
ring_buffer_size_t framesAvailable;
ring_buffer_size_t framesToTransfer;
ring_buffer_size_t framesTransferred;
do {
framesAvailable = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );
/*
printf( "Write Buffer is %%%g full: %ld of %ld.\n",
100 - 100 * (float)avail / (float) blio->outputRingBuffer.bufferSize,
framesAvailable, blio->outputRingBuffer.bufferSize );
*/
if( framesAvailable == 0 ) {
#ifdef PA_MAC_BLIO_MUTEX
/*block while full*/
ret = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) );
if( ret )
return ret;
while( blio->isOutputFull ) {
ret = UNIX_ERR( pthread_cond_wait( &blio->outputCond, &blio->outputMutex ) );
if( ret )
return ret;
}
ret = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) );
if( ret )
return ret;
#else
Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );
#endif
}
} while( framesAvailable == 0 && macStream->state != STOPPING );
if( macStream->state == STOPPING )
{
break;
}
framesToTransfer = MIN( framesAvailable, framesRequested );
framesTransferred = PaUtil_WriteRingBuffer( &blio->outputRingBuffer, (void *)cbuf, framesToTransfer );
cbuf += framesTransferred * blio->outputSampleSizeActual * blio->outChan;
framesRequested -= framesTransferred;
#ifdef PA_MAC_BLIO_MUTEX
if( framesToTransfer == framesAvailable ) {
/* we just filled up the buffer, so we need to mark it as filled. */
ret = blioSetIsOutputFull( blio, true );
if( ret )
return ret;
/* of course, in the meantime, we may have emptied the buffer, so
so check for that, too, to avoid a race condition. */
if( PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer ) ) {
blioSetIsOutputFull( blio, false );
/* FIXME remove or review this code, does not fix race, ret not set! */
if( ret )
return ret;
}
}
#endif
}
if ( macStream->state == STOPPING )
{
ret = paInternalError;
}
else if (ret == paNoError )
{
/* Test for underflow. */
ret = blio->statusFlags & paOutputUnderflow;
/* report underflow only once: */
if( ret )
{
OSAtomicAnd32( (uint32_t)(~paOutputUnderflow), &blio->statusFlags );
ret = paOutputUnderflowed;
}
}
return ret;
}
/*
* Wait until the data in the buffer has finished playing.
*/
PaError waitUntilBlioWriteBufferIsEmpty( PaMacBlio *blio, double sampleRate,
size_t framesPerBuffer )
{
PaError result = paNoError;
if( blio->outputRingBuffer.buffer ) {
ring_buffer_size_t framesLeft = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
/* Calculate when we should give up waiting. To be safe wait for two extra periods. */
PaTime now = PaUtil_GetTime();
PaTime startTime = now;
PaTime timeoutTime = startTime + (framesLeft + (2 * framesPerBuffer)) / sampleRate;
long msecPerBuffer = 1 + (long)( 1000.0 * framesPerBuffer / sampleRate);
while( framesLeft > 0 && now < timeoutTime ) {
VDBUG(( "waitUntilBlioWriteBufferIsFlushed: framesLeft = %d, framesPerBuffer = %ld\n",
framesLeft, framesPerBuffer ));
Pa_Sleep( msecPerBuffer );
framesLeft = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
now = PaUtil_GetTime();
}
if( framesLeft > 0 )
{
VDBUG(( "waitUntilBlioWriteBufferIsFlushed: TIMED OUT - framesLeft = %d\n", framesLeft ));
result = paTimedOut;
}
}
return result;
}
signed long GetStreamReadAvailable( PaStream* stream )
{
PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
VVDBUG(("GetStreamReadAvailable()\n"));
return PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer );
}
signed long GetStreamWriteAvailable( PaStream* stream )
{
PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
VVDBUG(("GetStreamWriteAvailable()\n"));
return PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );
}

View file

@ -0,0 +1,134 @@
/*
* Internal blocking interfaces for PortAudio Apple AUHAL implementation
*
* PortAudio Portable Real-Time Audio Library
* Latest Version at: http://www.portaudio.com
*
* Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
* Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
*
* Dominic's code was based on code by Phil Burk, Darren Gibbs,
* Gord Peters, Stephane Letz, and Greg Pfiel.
*
* The following people also deserve acknowledgements:
*
* Olivier Tristan for feedback and testing
* Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
* interface.
*
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/**
@file
@ingroup hostapi_src
*/
#ifndef PA_MAC_CORE_BLOCKING_H_
#define PA_MAC_CORE_BLOCKING_H_
#include "pa_ringbuffer.h"
#include "portaudio.h"
#include "pa_mac_core_utilities.h"
/*
* Number of milliseconds to busy wait while waiting for data in blocking calls.
*/
#define PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL (5)
/*
* Define exactly one of these blocking methods
* PA_MAC_BLIO_MUTEX is not actively maintained.
*/
#define PA_MAC_BLIO_BUSY_WAIT
/*
#define PA_MAC_BLIO_MUTEX
*/
typedef struct {
PaUtilRingBuffer inputRingBuffer;
PaUtilRingBuffer outputRingBuffer;
ring_buffer_size_t ringBufferFrames;
PaSampleFormat inputSampleFormat;
size_t inputSampleSizeActual;
size_t inputSampleSizePow2;
PaSampleFormat outputSampleFormat;
size_t outputSampleSizeActual;
size_t outputSampleSizePow2;
int inChan;
int outChan;
//PaStreamCallbackFlags statusFlags;
uint32_t statusFlags;
PaError errors;
/* Here we handle blocking, using condition variables. */
#ifdef PA_MAC_BLIO_MUTEX
volatile bool isInputEmpty;
pthread_mutex_t inputMutex;
pthread_cond_t inputCond;
volatile bool isOutputFull;
pthread_mutex_t outputMutex;
pthread_cond_t outputCond;
#endif
}
PaMacBlio;
/*
* These functions operate on condition and related variables.
*/
PaError initializeBlioRingBuffers(
PaMacBlio *blio,
PaSampleFormat inputSampleFormat,
PaSampleFormat outputSampleFormat,
long ringBufferSizeInFrames,
int inChan,
int outChan );
PaError destroyBlioRingBuffers( PaMacBlio *blio );
PaError resetBlioRingBuffers( PaMacBlio *blio );
int BlioCallback(
const void *input, void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData );
PaError waitUntilBlioWriteBufferIsEmpty( PaMacBlio *blio, double sampleRate,
size_t framesPerBuffer );
#endif /*PA_MAC_CORE_BLOCKING_H_*/

View file

@ -0,0 +1,193 @@
/*
* Internal interfaces for PortAudio Apple AUHAL implementation
*
* PortAudio Portable Real-Time Audio Library
* Latest Version at: http://www.portaudio.com
*
* Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
* Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
*
* Dominic's code was based on code by Phil Burk, Darren Gibbs,
* Gord Peters, Stephane Letz, and Greg Pfiel.
*
* The following people also deserve acknowledgements:
*
* Olivier Tristan for feedback and testing
* Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
* interface.
*
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/**
@file pa_mac_core
@ingroup hostapi_src
@author Bjorn Roche
@brief AUHAL implementation of PortAudio
*/
#ifndef PA_MAC_CORE_INTERNAL_H__
#define PA_MAC_CORE_INTERNAL_H__
#include <CoreAudio/CoreAudio.h>
#include <CoreServices/CoreServices.h>
#include <AudioUnit/AudioUnit.h>
#include <AudioToolbox/AudioToolbox.h>
#include "portaudio.h"
#include "pa_util.h"
#include "pa_hostapi.h"
#include "pa_stream.h"
#include "pa_allocation.h"
#include "pa_cpuload.h"
#include "pa_process.h"
#include "pa_ringbuffer.h"
#include "pa_mac_core_blocking.h"
/* function prototypes */
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
#ifdef __cplusplus
}
#endif /* __cplusplus */
#define RING_BUFFER_ADVANCE_DENOMINATOR (4)
PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
signed long GetStreamReadAvailable( PaStream* stream );
signed long GetStreamWriteAvailable( PaStream* stream );
/* PaMacAUHAL - host api datastructure specific to this implementation */
typedef struct
{
PaUtilHostApiRepresentation inheritedHostApiRep;
PaUtilStreamInterface callbackStreamInterface;
PaUtilStreamInterface blockingStreamInterface;
PaUtilAllocationGroup *allocations;
/* implementation specific data goes here */
long devCount;
AudioDeviceID *devIds; /*array of all audio devices*/
AudioDeviceID defaultIn;
AudioDeviceID defaultOut;
}
PaMacAUHAL;
typedef struct PaMacCoreDeviceProperties
{
/* Values in Frames from property queries. */
UInt32 safetyOffset;
UInt32 bufferFrameSize;
// UInt32 streamLatency; // Seems to be the same as deviceLatency!?
UInt32 deviceLatency;
/* Current device sample rate. May change!
These are initialized to the nominal device sample rate,
and updated with the actual sample rate, when/where available.
Note that these are the *device* sample rates, prior to any required
SR conversion. */
Float64 sampleRate;
Float64 samplePeriod; // reciprocal
}
PaMacCoreDeviceProperties;
/* stream data structure specifically for this implementation */
typedef struct PaMacCoreStream
{
PaUtilStreamRepresentation streamRepresentation;
PaUtilCpuLoadMeasurer cpuLoadMeasurer;
PaUtilBufferProcessor bufferProcessor;
/* implementation specific data goes here */
bool bufferProcessorIsInitialized;
AudioUnit inputUnit;
AudioUnit outputUnit;
AudioDeviceID inputDevice;
AudioDeviceID outputDevice;
size_t userInChan;
size_t userOutChan;
size_t inputFramesPerBuffer;
size_t outputFramesPerBuffer;
PaMacBlio blio;
/* We use this ring buffer when input and out devs are different. */
PaUtilRingBuffer inputRingBuffer;
/* We may need to do SR conversion on input. */
AudioConverterRef inputSRConverter;
/* We need to preallocate an inputBuffer for reading data. */
AudioBufferList inputAudioBufferList;
AudioTimeStamp startTime;
/* FIXME: instead of volatile, these should be properly memory barriered */
volatile uint32_t xrunFlags; /*PaStreamCallbackFlags*/
volatile enum {
STOPPED = 0, /* playback is completely stopped,
and the user has called StopStream(). */
CALLBACK_STOPPED = 1, /* callback has requested stop,
but user has not yet called StopStream(). */
STOPPING = 2, /* The stream is in the process of closing
because the user has called StopStream.
This state is just used internally;
externally it is indistinguishable from
ACTIVE.*/
ACTIVE = 3 /* The stream is active and running. */
} state;
double sampleRate;
PaMacCoreDeviceProperties inputProperties;
PaMacCoreDeviceProperties outputProperties;
/* data updated by main thread and notifications, protected by timingInformationMutex */
int timingInformationMutexIsInitialized;
pthread_mutex_t timingInformationMutex;
/* These are written by the PA thread or from CoreAudio callbacks. Protected by the mutex. */
Float64 timestampOffsetCombined;
Float64 timestampOffsetInputDevice;
Float64 timestampOffsetOutputDevice;
/* Offsets in seconds to be applied to Apple timestamps to convert them to PA timestamps.
* While the io proc is active, the following values are only accessed and manipulated by the ioproc */
Float64 timestampOffsetCombined_ioProcCopy;
Float64 timestampOffsetInputDevice_ioProcCopy;
Float64 timestampOffsetOutputDevice_ioProcCopy;
}
PaMacCoreStream;
#endif /* PA_MAC_CORE_INTERNAL_H__ */

View file

@ -0,0 +1,814 @@
/*
* Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation)
*
* PortAudio Portable Real-Time Audio Library
* Latest Version at: http://www.portaudio.com
*
* Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
* Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
*
* Dominic's code was based on code by Phil Burk, Darren Gibbs,
* Gord Peters, Stephane Letz, and Greg Pfiel.
*
* The following people also deserve acknowledgements:
*
* Olivier Tristan for feedback and testing
* Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
* interface.
*
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/**
@file
@ingroup hostapi_src
*/
#include "pa_mac_core_utilities.h"
#include "pa_mac_core_internal.h"
#include <libkern/OSAtomic.h>
#include <strings.h>
#include <pthread.h>
#include <sys/time.h>
OSStatus PaMacCore_AudioHardwareGetProperty(
AudioHardwarePropertyID inPropertyID,
UInt32* ioPropertyDataSize,
void* outPropertyData )
{
AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
return AudioObjectGetPropertyData(kAudioObjectSystemObject, &address, 0, NULL, ioPropertyDataSize, outPropertyData);
}
OSStatus PaMacCore_AudioHardwareGetPropertySize(
AudioHardwarePropertyID inPropertyID,
UInt32* outSize )
{
AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
return AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &address, 0, NULL, outSize);
}
OSStatus PaMacCore_AudioDeviceGetProperty(
AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
UInt32* ioPropertyDataSize,
void* outPropertyData )
{
AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
return AudioObjectGetPropertyData(inDevice, &address, 0, NULL, ioPropertyDataSize, outPropertyData);
}
OSStatus PaMacCore_AudioDeviceSetProperty(
AudioDeviceID inDevice,
const AudioTimeStamp* inWhen,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void* inPropertyData )
{
AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
return AudioObjectSetPropertyData(inDevice, &address, 0, NULL, inPropertyDataSize, inPropertyData);
}
OSStatus PaMacCore_AudioDeviceGetPropertySize(
AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
UInt32* outSize )
{
AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
return AudioObjectGetPropertyDataSize(inDevice, &address, 0, NULL, outSize);
}
OSStatus PaMacCore_AudioDeviceAddPropertyListener(
AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
AudioObjectPropertyListenerProc inProc,
void* inClientData )
{
AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
return AudioObjectAddPropertyListener(inDevice, &address, inProc, inClientData);
}
OSStatus PaMacCore_AudioDeviceRemovePropertyListener(
AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
AudioObjectPropertyListenerProc inProc,
void* inClientData )
{
AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
return AudioObjectRemovePropertyListener(inDevice, &address, inProc, inClientData);
}
OSStatus PaMacCore_AudioStreamGetProperty(
AudioStreamID inStream,
UInt32 inChannel,
AudioDevicePropertyID inPropertyID,
UInt32* ioPropertyDataSize,
void* outPropertyData )
{
AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
return AudioObjectGetPropertyData(inStream, &address, 0, NULL, ioPropertyDataSize, outPropertyData);
}
PaError PaMacCore_SetUnixError( int err, int line )
{
PaError ret;
const char *errorText;
if( err == 0 )
{
return paNoError;
}
ret = paNoError;
errorText = strerror( err );
/** Map Unix error to PaError. Pretty much the only one that maps
is ENOMEM. */
if( err == ENOMEM )
ret = paInsufficientMemory;
else
ret = paInternalError;
DBUG(("%d on line %d: msg='%s'\n", err, line, errorText));
PaUtil_SetLastHostErrorInfo( paCoreAudio, err, errorText );
return ret;
}
/*
* Translates MacOS generated errors into PaErrors
*/
PaError PaMacCore_SetError(OSStatus error, int line, int isError)
{
/*FIXME: still need to handle possible ComponentResult values.*/
/* unfortunately, they don't seem to be documented anywhere.*/
PaError result;
const char *errorType;
const char *errorText;
switch (error) {
case kAudioHardwareNoError:
return paNoError;
case kAudioHardwareNotRunningError:
errorText = "Audio Hardware Not Running";
result = paInternalError;
break;
case kAudioHardwareUnspecifiedError:
errorText = "Unspecified Audio Hardware Error";
result = paInternalError;
break;
case kAudioHardwareUnknownPropertyError:
errorText = "Audio Hardware: Unknown Property";
result = paInternalError;
break;
case kAudioHardwareBadPropertySizeError:
errorText = "Audio Hardware: Bad Property Size";
result = paInternalError;
break;
case kAudioHardwareIllegalOperationError:
errorText = "Audio Hardware: Illegal Operation";
result = paInternalError;
break;
case kAudioHardwareBadDeviceError:
errorText = "Audio Hardware: Bad Device";
result = paInvalidDevice;
break;
case kAudioHardwareBadStreamError:
errorText = "Audio Hardware: BadStream";
result = paBadStreamPtr;
break;
case kAudioHardwareUnsupportedOperationError:
errorText = "Audio Hardware: Unsupported Operation";
result = paInternalError;
break;
case kAudioDeviceUnsupportedFormatError:
errorText = "Audio Device: Unsupported Format";
result = paSampleFormatNotSupported;
break;
case kAudioDevicePermissionsError:
errorText = "Audio Device: Permissions Error";
result = paDeviceUnavailable;
break;
/* Audio Unit Errors: http://developer.apple.com/documentation/MusicAudio/Reference/CoreAudio/audio_units/chapter_5_section_3.html */
case kAudioUnitErr_InvalidProperty:
errorText = "Audio Unit: Invalid Property";
result = paInternalError;
break;
case kAudioUnitErr_InvalidParameter:
errorText = "Audio Unit: Invalid Parameter";
result = paInternalError;
break;
case kAudioUnitErr_NoConnection:
errorText = "Audio Unit: No Connection";
result = paInternalError;
break;
case kAudioUnitErr_FailedInitialization:
errorText = "Audio Unit: Initialization Failed";
result = paInternalError;
break;
case kAudioUnitErr_TooManyFramesToProcess:
errorText = "Audio Unit: Too Many Frames";
result = paInternalError;
break;
case kAudioUnitErr_InvalidFile:
errorText = "Audio Unit: Invalid File";
result = paInternalError;
break;
case kAudioUnitErr_UnknownFileType:
errorText = "Audio Unit: Unknown File Type";
result = paInternalError;
break;
case kAudioUnitErr_FileNotSpecified:
errorText = "Audio Unit: File Not Specified";
result = paInternalError;
break;
case kAudioUnitErr_FormatNotSupported:
errorText = "Audio Unit: Format Not Supported";
result = paInternalError;
break;
case kAudioUnitErr_Uninitialized:
errorText = "Audio Unit: Uninitialized";
result = paInternalError;
break;
case kAudioUnitErr_InvalidScope:
errorText = "Audio Unit: Invalid Scope";
result = paInternalError;
break;
case kAudioUnitErr_PropertyNotWritable:
errorText = "Audio Unit: PropertyNotWritable";
result = paInternalError;
break;
case kAudioUnitErr_InvalidPropertyValue:
errorText = "Audio Unit: Invalid Property Value";
result = paInternalError;
break;
case kAudioUnitErr_PropertyNotInUse:
errorText = "Audio Unit: Property Not In Use";
result = paInternalError;
break;
case kAudioUnitErr_Initialized:
errorText = "Audio Unit: Initialized";
result = paInternalError;
break;
case kAudioUnitErr_InvalidOfflineRender:
errorText = "Audio Unit: Invalid Offline Render";
result = paInternalError;
break;
case kAudioUnitErr_Unauthorized:
errorText = "Audio Unit: Unauthorized";
result = paInternalError;
break;
case kAudioUnitErr_CannotDoInCurrentContext:
errorText = "Audio Unit: cannot do in current context";
result = paInternalError;
break;
default:
errorText = "Unknown Error";
result = paInternalError;
}
if (isError)
errorType = "Error";
else
errorType = "Warning";
char str[20];
// see if it appears to be a 4-char-code
*(UInt32 *)(str + 1) = CFSwapInt32HostToBig(error);
if (isprint(str[1]) && isprint(str[2]) && isprint(str[3]) && isprint(str[4]))
{
str[0] = str[5] = '\'';
str[6] = '\0';
} else {
// no, format it as an integer
sprintf(str, "%d", (int)error);
}
DBUG(("%s on line %d: err='%s', msg=%s\n", errorType, line, str, errorText));
PaUtil_SetLastHostErrorInfo( paCoreAudio, error, errorText );
return result;
}
/*
* This function computes an appropriate ring buffer size given
* a requested latency (in seconds), sample rate and framesPerBuffer.
*
* The returned ringBufferSize is computed using the following
* constraints:
* - it must be at least 4.
* - it must be at least 3x framesPerBuffer.
* - it must be at least 2x the suggestedLatency.
* - it must be a power of 2.
* This function attempts to compute the minimum such size.
*
* FEEDBACK: too liberal/conservative/another way?
*/
long computeRingBufferSize( const PaStreamParameters *inputParameters,
const PaStreamParameters *outputParameters,
long inputFramesPerBuffer,
long outputFramesPerBuffer,
double sampleRate )
{
long ringSize;
int index;
int i;
double latency ;
long framesPerBuffer ;
VVDBUG(( "computeRingBufferSize()\n" ));
assert( inputParameters || outputParameters );
if( outputParameters && inputParameters )
{
latency = MAX( inputParameters->suggestedLatency, outputParameters->suggestedLatency );
framesPerBuffer = MAX( inputFramesPerBuffer, outputFramesPerBuffer );
}
else if( outputParameters )
{
latency = outputParameters->suggestedLatency;
framesPerBuffer = outputFramesPerBuffer ;
}
else /* we have inputParameters */
{
latency = inputParameters->suggestedLatency;
framesPerBuffer = inputFramesPerBuffer ;
}
ringSize = (long) ( latency * sampleRate * 2 + .5);
VDBUG( ( "suggested latency : %d\n", (int) (latency*sampleRate) ) );
if( ringSize < framesPerBuffer * 3 )
ringSize = framesPerBuffer * 3 ;
VDBUG(("framesPerBuffer:%d\n",(int)framesPerBuffer));
VDBUG(("Ringbuffer size (1): %d\n", (int)ringSize ));
/* make sure it's at least 4 */
ringSize = MAX( ringSize, 4 );
/* round up to the next power of 2 */
index = -1;
for( i=0; i<sizeof(long)*8; ++i )
if( ringSize >> i & 0x01 )
index = i;
assert( index > 0 );
if( ringSize <= ( 0x01 << index ) )
ringSize = 0x01 << index ;
else
ringSize = 0x01 << ( index + 1 );
VDBUG(( "Final Ringbuffer size (2): %d\n", (int)ringSize ));
return ringSize;
}
/*
* During testing of core audio, I found that serious crashes could occur
* if properties such as sample rate were changed multiple times in rapid
* succession. The function below could be used to with a condition variable.
* to prevent propertychanges from happening until the last property
* change is acknowledged. Instead, I implemented a busy-wait, which is simpler
* to implement b/c in second round of testing (nov '09) property changes occurred
* quickly and so there was no real way to test the condition variable implementation.
* therefore, this function is not used, but it is aluded to in commented code below,
* since it represents a theoretically better implementation.
*/
OSStatus propertyProc(
AudioObjectID inObjectID,
UInt32 inNumberAddresses,
const AudioObjectPropertyAddress* inAddresses,
void* inClientData )
{
// this is where we would set the condition variable
return noErr;
}
/* sets the value of the given property and waits for the change to
be acknowledged, and returns the final value, which is not guaranteed
by this function to be the same as the desired value. Obviously, this
function can only be used for data whose input and output are the
same size and format, and their size and format are known in advance.
whether or not the call succeeds, if the data is successfully read,
it is returned in outPropertyData. If it is not read successfully,
outPropertyData is zeroed, which may or may not be useful in
determining if the property was read. */
PaError AudioDeviceSetPropertyNowAndWaitForChange(
AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void *inPropertyData,
void *outPropertyData )
{
OSStatus macErr;
UInt32 outPropertyDataSize = inPropertyDataSize;
/* First, see if it already has that value. If so, return. */
macErr = PaMacCore_AudioDeviceGetProperty( inDevice, inChannel,
isInput, inPropertyID,
&outPropertyDataSize, outPropertyData );
if( macErr ) {
memset( outPropertyData, 0, inPropertyDataSize );
goto failMac;
}
if( inPropertyDataSize!=outPropertyDataSize )
return paInternalError;
if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) )
return paNoError;
/* Ideally, we'd use a condition variable to determine changes.
we could set that up here. */
/* If we were using a cond variable, we'd do something useful here,
but for now, this is just to make 10.6 happy. */
macErr = PaMacCore_AudioDeviceAddPropertyListener( inDevice, inChannel, isInput,
inPropertyID, propertyProc,
NULL );
if( macErr )
/* we couldn't add a listener. */
goto failMac;
/* set property */
macErr = PaMacCore_AudioDeviceSetProperty( inDevice, NULL, inChannel,
isInput, inPropertyID,
inPropertyDataSize, inPropertyData );
if( macErr )
goto failMac;
/* busy-wait up to 30 seconds for the property to change */
/* busy-wait is justified here only because the correct alternative (condition variable)
was hard to test, since most of the waiting ended up being for setting rather than
getting in OS X 10.5. This was not the case in earlier OS versions. */
struct timeval tv1, tv2;
gettimeofday( &tv1, NULL );
memcpy( &tv2, &tv1, sizeof( struct timeval ) );
while( tv2.tv_sec - tv1.tv_sec < 30 ) {
/* now read the property back out */
macErr = PaMacCore_AudioDeviceGetProperty( inDevice, inChannel,
isInput, inPropertyID,
&outPropertyDataSize, outPropertyData );
if( macErr ) {
memset( outPropertyData, 0, inPropertyDataSize );
goto failMac;
}
/* and compare... */
if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) ) {
PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL);
return paNoError;
}
/* No match yet, so let's sleep and try again. */
Pa_Sleep( 100 );
gettimeofday( &tv2, NULL );
}
DBUG( ("Timeout waiting for device setting.\n" ) );
PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL );
return paNoError;
failMac:
PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL );
return ERR( macErr );
}
/*
* Sets the sample rate the HAL device.
* if requireExact: set the sample rate or fail.
*
* otherwise : set the exact sample rate.
* If that fails, check for available sample rates, and choose one
* higher than the requested rate. If there isn't a higher one,
* just use the highest available.
*/
PaError setBestSampleRateForDevice( const AudioDeviceID device,
const bool isOutput,
const bool requireExact,
const Float64 desiredSrate )
{
const bool isInput = isOutput ? 0 : 1;
Float64 srate;
UInt32 propsize = sizeof( Float64 );
OSErr err;
AudioValueRange *ranges;
int i=0;
Float64 max = -1; /*the maximum rate available*/
Float64 best = -1; /*the lowest sample rate still greater than desired rate*/
VDBUG(("Setting sample rate for device %ld to %g.\n",(long)device,(float)desiredSrate));
/* -- try setting the sample rate -- */
srate = 0;
err = AudioDeviceSetPropertyNowAndWaitForChange(
device, 0, isInput,
kAudioDevicePropertyNominalSampleRate,
propsize, &desiredSrate, &srate );
/* -- if the rate agrees, and was changed, we are done -- */
if( srate != 0 && srate == desiredSrate )
return paNoError;
/* -- if the rate agrees, and we got no errors, we are done -- */
if( !err && srate == desiredSrate )
return paNoError;
/* -- we've failed if the rates disagree and we are setting input -- */
if( requireExact )
return paInvalidSampleRate;
/* -- generate a list of available sample rates -- */
err = PaMacCore_AudioDeviceGetPropertySize( device, 0, isInput,
kAudioDevicePropertyAvailableNominalSampleRates,
&propsize );
if( err )
return ERR( err );
ranges = (AudioValueRange *)calloc( 1, propsize );
if( !ranges )
return paInsufficientMemory;
err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
kAudioDevicePropertyAvailableNominalSampleRates,
&propsize, ranges );
if( err )
{
free( ranges );
return ERR( err );
}
VDBUG(("Requested sample rate of %g was not available.\n", (float)desiredSrate));
VDBUG(("%lu Available Sample Rates are:\n",propsize/sizeof(AudioValueRange)));
#ifdef MAC_CORE_VERBOSE_DEBUG
for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
VDBUG( ("\t%g-%g\n",
(float) ranges[i].mMinimum,
(float) ranges[i].mMaximum ) );
#endif
VDBUG(("-----\n"));
/* -- now pick the best available sample rate -- */
for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
{
if( ranges[i].mMaximum > max ) max = ranges[i].mMaximum;
if( ranges[i].mMinimum > desiredSrate ) {
if( best < 0 )
best = ranges[i].mMinimum;
else if( ranges[i].mMinimum < best )
best = ranges[i].mMinimum;
}
}
if( best < 0 )
best = max;
VDBUG( ("Maximum Rate %g. best is %g.\n", max, best ) );
free( ranges );
/* -- set the sample rate -- */
propsize = sizeof( best );
srate = 0;
err = AudioDeviceSetPropertyNowAndWaitForChange(
device, 0, isInput,
kAudioDevicePropertyNominalSampleRate,
propsize, &best, &srate );
/* -- if the set rate matches, we are done -- */
if( srate != 0 && srate == best )
return paNoError;
if( err )
return ERR( err );
/* -- otherwise, something weird happened: we didn't set the rate, and we got no errors. Just bail. */
return paInternalError;
}
/*
Attempts to set the requestedFramesPerBuffer. If it can't set the exact
value, it settles for something smaller if available. If nothing smaller
is available, it uses the smallest available size.
actualFramesPerBuffer will be set to the actual value on successful return.
OK to pass NULL to actualFramesPerBuffer.
The logic is very similar too setBestSampleRate only failure here is
not usually catastrophic.
*/
PaError setBestFramesPerBuffer( const AudioDeviceID device,
const bool isOutput,
UInt32 requestedFramesPerBuffer,
UInt32 *actualFramesPerBuffer )
{
UInt32 afpb;
const bool isInput = !isOutput;
UInt32 propsize = sizeof(UInt32);
OSErr err;
AudioValueRange range;
if( actualFramesPerBuffer == NULL )
{
actualFramesPerBuffer = &afpb;
}
/* -- try and set exact FPB -- */
err = PaMacCore_AudioDeviceSetProperty( device, NULL, 0, isInput,
kAudioDevicePropertyBufferFrameSize,
propsize, &requestedFramesPerBuffer);
err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
kAudioDevicePropertyBufferFrameSize,
&propsize, actualFramesPerBuffer);
if( err )
{
return ERR( err );
}
// Did we get the size we asked for?
if( *actualFramesPerBuffer == requestedFramesPerBuffer )
{
return paNoError; /* we are done */
}
// Clip requested value against legal range for the device.
propsize = sizeof(AudioValueRange);
err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
kAudioDevicePropertyBufferFrameSizeRange,
&propsize, &range );
if( err )
{
return ERR( err );
}
if( requestedFramesPerBuffer < range.mMinimum )
{
requestedFramesPerBuffer = range.mMinimum;
}
else if( requestedFramesPerBuffer > range.mMaximum )
{
requestedFramesPerBuffer = range.mMaximum;
}
/* --- set the buffer size (ignore errors) -- */
propsize = sizeof( UInt32 );
err = PaMacCore_AudioDeviceSetProperty( device, NULL, 0, isInput,
kAudioDevicePropertyBufferFrameSize,
propsize, &requestedFramesPerBuffer );
/* --- read the property to check that it was set -- */
err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
kAudioDevicePropertyBufferFrameSize,
&propsize, actualFramesPerBuffer );
if( err )
return ERR( err );
return paNoError;
}
/**********************
*
* XRun stuff
*
**********************/
struct PaMacXRunListNode_s {
PaMacCoreStream *stream;
struct PaMacXRunListNode_s *next;
} ;
typedef struct PaMacXRunListNode_s PaMacXRunListNode;
/** Always empty, so that it can always be the one returned by
addToXRunListenerList. note that it's not a pointer. */
static PaMacXRunListNode firstXRunListNode;
static int xRunListSize;
static pthread_mutex_t xrunMutex;
OSStatus xrunCallback(
AudioObjectID inDevice,
UInt32 inNumberAddresses,
const AudioObjectPropertyAddress* inAddresses,
void * inClientData)
{
PaMacXRunListNode *node = (PaMacXRunListNode *) inClientData;
bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput;
int ret = pthread_mutex_trylock( &xrunMutex ) ;
if( ret == 0 ) {
node = node->next ; //skip the first node
for( ; node; node=node->next ) {
PaMacCoreStream *stream = node->stream;
if( stream->state != ACTIVE )
continue; //if the stream isn't active, we don't care if the device is dropping
if( isInput ) {
if( stream->inputDevice == inDevice )
OSAtomicOr32( paInputOverflow, &stream->xrunFlags );
} else {
if( stream->outputDevice == inDevice )
OSAtomicOr32( paOutputUnderflow, &stream->xrunFlags );
}
}
pthread_mutex_unlock( &xrunMutex );
}
return 0;
}
int initializeXRunListenerList( void )
{
xRunListSize = 0;
bzero( (void *) &firstXRunListNode, sizeof(firstXRunListNode) );
return pthread_mutex_init( &xrunMutex, NULL );
}
int destroyXRunListenerList( void )
{
PaMacXRunListNode *node;
node = firstXRunListNode.next;
while( node ) {
PaMacXRunListNode *tmp = node;
node = node->next;
free( tmp );
}
xRunListSize = 0;
return pthread_mutex_destroy( &xrunMutex );
}
void *addToXRunListenerList( void *stream )
{
pthread_mutex_lock( &xrunMutex );
PaMacXRunListNode *newNode;
// setup new node:
newNode = (PaMacXRunListNode *) malloc( sizeof( PaMacXRunListNode ) );
newNode->stream = (PaMacCoreStream *) stream;
newNode->next = firstXRunListNode.next;
// insert:
firstXRunListNode.next = newNode;
pthread_mutex_unlock( &xrunMutex );
return &firstXRunListNode;
}
int removeFromXRunListenerList( void *stream )
{
pthread_mutex_lock( &xrunMutex );
PaMacXRunListNode *node, *prev;
prev = &firstXRunListNode;
node = firstXRunListNode.next;
while( node ) {
if( node->stream == stream ) {
//found it:
--xRunListSize;
prev->next = node->next;
free( node );
pthread_mutex_unlock( &xrunMutex );
return xRunListSize;
}
prev = prev->next;
node = node->next;
}
pthread_mutex_unlock( &xrunMutex );
// failure
return xRunListSize;
}

View file

@ -0,0 +1,268 @@
/*
* Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation)
*
* PortAudio Portable Real-Time Audio Library
* Latest Version at: http://www.portaudio.com
*
* Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
* Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
*
* Dominic's code was based on code by Phil Burk, Darren Gibbs,
* Gord Peters, Stephane Letz, and Greg Pfiel.
*
* The following people also deserve acknowledgements:
*
* Olivier Tristan for feedback and testing
* Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
* interface.
*
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Ross Bencina, Phil Burk
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/**
@file
@ingroup hostapi_src
*/
#ifndef PA_MAC_CORE_UTILITIES_H__
#define PA_MAC_CORE_UTILITIES_H__
#include <pthread.h>
#include "portaudio.h"
#include "pa_util.h"
#include <AudioUnit/AudioUnit.h>
#include <AudioToolbox/AudioToolbox.h>
#ifndef MIN
#define MIN(a, b) (((a)<(b))?(a):(b))
#endif
#ifndef MAX
#define MAX(a, b) (((a)<(b))?(b):(a))
#endif
#define ERR(mac_error) PaMacCore_SetError(mac_error, __LINE__, 1 )
#define WARNING(mac_error) PaMacCore_SetError(mac_error, __LINE__, 0 )
/* Help keep track of AUHAL element numbers */
#define INPUT_ELEMENT (1)
#define OUTPUT_ELEMENT (0)
/* Normal level of debugging: fine for most apps that don't mind the occasional warning being printf'ed */
/*
*/
#define MAC_CORE_DEBUG
#ifdef MAC_CORE_DEBUG
# define DBUG(MSG) do { printf("||PaMacCore (AUHAL)|| "); printf MSG ; fflush(stdout); } while(0)
#else
# define DBUG(MSG)
#endif
/* Verbose Debugging: useful for development */
/*
#define MAC_CORE_VERBOSE_DEBUG
*/
#ifdef MAC_CORE_VERBOSE_DEBUG
# define VDBUG(MSG) do { printf("||PaMacCore (v )|| "); printf MSG ; fflush(stdout); } while(0)
#else
# define VDBUG(MSG)
#endif
/* Very Verbose Debugging: Traces every call. */
/*
#define MAC_CORE_VERY_VERBOSE_DEBUG
*/
#ifdef MAC_CORE_VERY_VERBOSE_DEBUG
# define VVDBUG(MSG) do { printf("||PaMacCore (vv)|| "); printf MSG ; fflush(stdout); } while(0)
#else
# define VVDBUG(MSG)
#endif
OSStatus PaMacCore_AudioHardwareGetProperty(
AudioHardwarePropertyID inPropertyID,
UInt32* ioPropertyDataSize,
void* outPropertyData );
OSStatus PaMacCore_AudioHardwareGetPropertySize(
AudioHardwarePropertyID inPropertyID,
UInt32* outSize );
OSStatus PaMacCore_AudioDeviceGetProperty(
AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
UInt32* ioPropertyDataSize,
void* outPropertyData );
OSStatus PaMacCore_AudioDeviceSetProperty(
AudioDeviceID inDevice,
const AudioTimeStamp* inWhen,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void* inPropertyData );
OSStatus PaMacCore_AudioDeviceGetPropertySize(
AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
UInt32* outSize );
OSStatus PaMacCore_AudioDeviceAddPropertyListener(
AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
AudioObjectPropertyListenerProc inProc,
void* inClientData );
OSStatus PaMacCore_AudioDeviceRemovePropertyListener(
AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
AudioObjectPropertyListenerProc inProc,
void* inClientData );
OSStatus PaMacCore_AudioStreamGetProperty(
AudioStreamID inStream,
UInt32 inChannel,
AudioDevicePropertyID inPropertyID,
UInt32* ioPropertyDataSize,
void* outPropertyData );
#define UNIX_ERR(err) PaMacCore_SetUnixError( err, __LINE__ )
PaError PaMacCore_SetUnixError( int err, int line );
/*
* Translates MacOS generated errors into PaErrors
*/
PaError PaMacCore_SetError(OSStatus error, int line, int isError);
/*
* This function computes an appropriate ring buffer size given
* a requested latency (in seconds), sample rate and framesPerBuffer.
*
* The returned ringBufferSize is computed using the following
* constraints:
* - it must be at least 4.
* - it must be at least 3x framesPerBuffer.
* - it must be at least 2x the suggestedLatency.
* - it must be a power of 2.
* This function attempts to compute the minimum such size.
*
*/
long computeRingBufferSize( const PaStreamParameters *inputParameters,
const PaStreamParameters *outputParameters,
long inputFramesPerBuffer,
long outputFramesPerBuffer,
double sampleRate );
OSStatus propertyProc(
AudioObjectID inObjectID,
UInt32 inNumberAddresses,
const AudioObjectPropertyAddress* inAddresses,
void* inClientData );
/* sets the value of the given property and waits for the change to
be acknowledged, and returns the final value, which is not guaranteed
by this function to be the same as the desired value. Obviously, this
function can only be used for data whose input and output are the
same size and format, and their size and format are known in advance.*/
PaError AudioDeviceSetPropertyNowAndWaitForChange(
AudioDeviceID inDevice,
UInt32 inChannel,
Boolean isInput,
AudioDevicePropertyID inPropertyID,
UInt32 inPropertyDataSize,
const void *inPropertyData,
void *outPropertyData );
/*
* Sets the sample rate the HAL device.
* if requireExact: set the sample rate or fail.
*
* otherwise : set the exact sample rate.
* If that fails, check for available sample rates, and choose one
* higher than the requested rate. If there isn't a higher one,
* just use the highest available.
*/
PaError setBestSampleRateForDevice( const AudioDeviceID device,
const bool isOutput,
const bool requireExact,
const Float64 desiredSrate );
/*
Attempts to set the requestedFramesPerBuffer. If it can't set the exact
value, it settles for something smaller if available. If nothing smaller
is available, it uses the smallest available size.
actualFramesPerBuffer will be set to the actual value on successful return.
OK to pass NULL to actualFramesPerBuffer.
The logic is very similar too setBestSampleRate only failure here is
not usually catastrophic.
*/
PaError setBestFramesPerBuffer( const AudioDeviceID device,
const bool isOutput,
UInt32 requestedFramesPerBuffer,
UInt32 *actualFramesPerBuffer );
/*********************
*
* xrun handling
*
*********************/
OSStatus xrunCallback(
AudioObjectID inObjectID,
UInt32 inNumberAddresses,
const AudioObjectPropertyAddress* inAddresses,
void * inClientData );
/** returns zero on success or a unix style error code. */
int initializeXRunListenerList( void );
/** returns zero on success or a unix style error code. */
int destroyXRunListenerList( void );
/**Returns the list, so that it can be passed to CorAudio.*/
void *addToXRunListenerList( void *stream );
/**Returns the number of Listeners in the list remaining.*/
int removeFromXRunListenerList( void *stream );
#endif /* PA_MAC_CORE_UTILITIES_H__*/

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,224 @@
/*
* Interface for dynamically loading directsound and providing a dummy
* implementation if it isn't present.
*
* Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi)
*
* For PortAudio Portable Real-Time Audio Library
* For more information see: http://www.portaudio.com
* Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/**
@file
@ingroup hostapi_src
*/
#include "pa_win_ds_dynlink.h"
#include "pa_debugprint.h"
PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints = { 0, 0, 0, 0, 0, 0, 0 };
static HRESULT WINAPI DummyDllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
{
(void)rclsid; /* unused parameter */
(void)riid; /* unused parameter */
(void)ppv; /* unused parameter */
return CLASS_E_CLASSNOTAVAILABLE;
}
static HRESULT WINAPI DummyDirectSoundCreate(LPGUID lpcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter)
{
(void)lpcGuidDevice; /* unused parameter */
(void)ppDS; /* unused parameter */
(void)pUnkOuter; /* unused parameter */
return E_NOTIMPL;
}
static HRESULT WINAPI DummyDirectSoundEnumerateW(LPDSENUMCALLBACKW lpDSEnumCallback, LPVOID lpContext)
{
(void)lpDSEnumCallback; /* unused parameter */
(void)lpContext; /* unused parameter */
return E_NOTIMPL;
}
static HRESULT WINAPI DummyDirectSoundEnumerateA(LPDSENUMCALLBACKA lpDSEnumCallback, LPVOID lpContext)
{
(void)lpDSEnumCallback; /* unused parameter */
(void)lpContext; /* unused parameter */
return E_NOTIMPL;
}
static HRESULT WINAPI DummyDirectSoundCaptureCreate(LPGUID lpcGUID, LPDIRECTSOUNDCAPTURE *lplpDSC, LPUNKNOWN pUnkOuter)
{
(void)lpcGUID; /* unused parameter */
(void)lplpDSC; /* unused parameter */
(void)pUnkOuter; /* unused parameter */
return E_NOTIMPL;
}
static HRESULT WINAPI DummyDirectSoundCaptureEnumerateW(LPDSENUMCALLBACKW lpDSCEnumCallback, LPVOID lpContext)
{
(void)lpDSCEnumCallback; /* unused parameter */
(void)lpContext; /* unused parameter */
return E_NOTIMPL;
}
static HRESULT WINAPI DummyDirectSoundCaptureEnumerateA(LPDSENUMCALLBACKA lpDSCEnumCallback, LPVOID lpContext)
{
(void)lpDSCEnumCallback; /* unused parameter */
(void)lpContext; /* unused parameter */
return E_NOTIMPL;
}
#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
static HRESULT WINAPI DummyDirectSoundFullDuplexCreate8(
LPCGUID pcGuidCaptureDevice,
LPCGUID pcGuidRenderDevice,
LPCDSCBUFFERDESC pcDSCBufferDesc,
LPCDSBUFFERDESC pcDSBufferDesc,
HWND hWnd,
DWORD dwLevel,
LPDIRECTSOUNDFULLDUPLEX * ppDSFD,
LPDIRECTSOUNDCAPTUREBUFFER8 * ppDSCBuffer8,
LPDIRECTSOUNDBUFFER8 * ppDSBuffer8,
LPUNKNOWN pUnkOuter)
{
(void)pcGuidCaptureDevice; /* unused parameter */
(void)pcGuidRenderDevice; /* unused parameter */
(void)pcDSCBufferDesc; /* unused parameter */
(void)pcDSBufferDesc; /* unused parameter */
(void)hWnd; /* unused parameter */
(void)dwLevel; /* unused parameter */
(void)ppDSFD; /* unused parameter */
(void)ppDSCBuffer8; /* unused parameter */
(void)ppDSBuffer8; /* unused parameter */
(void)pUnkOuter; /* unused parameter */
return E_NOTIMPL;
}
#endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */
void PaWinDs_InitializeDSoundEntryPoints(void)
{
paWinDsDSoundEntryPoints.hInstance_ = LoadLibraryA("dsound.dll");
if( paWinDsDSoundEntryPoints.hInstance_ != NULL )
{
paWinDsDSoundEntryPoints.DllGetClassObject =
(HRESULT (WINAPI *)(REFCLSID, REFIID , LPVOID *))
GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DllGetClassObject" );
if( paWinDsDSoundEntryPoints.DllGetClassObject == NULL )
paWinDsDSoundEntryPoints.DllGetClassObject = DummyDllGetClassObject;
paWinDsDSoundEntryPoints.DirectSoundCreate =
(HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN))
GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCreate" );
if( paWinDsDSoundEntryPoints.DirectSoundCreate == NULL )
paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate;
paWinDsDSoundEntryPoints.DirectSoundEnumerateW =
(HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID))
GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateW" );
if( paWinDsDSoundEntryPoints.DirectSoundEnumerateW == NULL )
paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW;
paWinDsDSoundEntryPoints.DirectSoundEnumerateA =
(HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID))
GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateA" );
if( paWinDsDSoundEntryPoints.DirectSoundEnumerateA == NULL )
paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA;
paWinDsDSoundEntryPoints.DirectSoundCaptureCreate =
(HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN))
GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureCreate" );
if( paWinDsDSoundEntryPoints.DirectSoundCaptureCreate == NULL )
paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate;
paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW =
(HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID))
GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateW" );
if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW == NULL )
paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW;
paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA =
(HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID))
GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateA" );
if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA == NULL )
paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA;
#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 =
(HRESULT (WINAPI *)(LPCGUID, LPCGUID, LPCDSCBUFFERDESC, LPCDSBUFFERDESC,
HWND, DWORD, LPDIRECTSOUNDFULLDUPLEX *, LPDIRECTSOUNDCAPTUREBUFFER8 *,
LPDIRECTSOUNDBUFFER8 *, LPUNKNOWN))
GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundFullDuplexCreate" );
if( paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 == NULL )
paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 = DummyDirectSoundFullDuplexCreate8;
#endif
}
else
{
DWORD errorCode = GetLastError(); // 126 (0x7E) == ERROR_MOD_NOT_FOUND
PA_DEBUG(("Couldn't load dsound.dll error code: %d \n",errorCode));
/* initialize with dummy entry points to make live easy when ds isn't present */
paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate;
paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW;
paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA;
paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate;
paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW;
paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA;
#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 = DummyDirectSoundFullDuplexCreate8;
#endif
}
}
void PaWinDs_TerminateDSoundEntryPoints(void)
{
if( paWinDsDSoundEntryPoints.hInstance_ != NULL )
{
/* ensure that we crash reliably if the entry points aren't initialised */
paWinDsDSoundEntryPoints.DirectSoundCreate = 0;
paWinDsDSoundEntryPoints.DirectSoundEnumerateW = 0;
paWinDsDSoundEntryPoints.DirectSoundEnumerateA = 0;
paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = 0;
paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = 0;
paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = 0;
FreeLibrary( paWinDsDSoundEntryPoints.hInstance_ );
paWinDsDSoundEntryPoints.hInstance_ = NULL;
}
}

View file

@ -0,0 +1,106 @@
/*
* Interface for dynamically loading directsound and providing a dummy
* implementation if it isn't present.
*
* Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi)
*
* For PortAudio Portable Real-Time Audio Library
* For more information see: http://www.portaudio.com
* Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina
*
* 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.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/**
@file
@ingroup hostapi_src
*/
#ifndef INCLUDED_PA_DSOUND_DYNLINK_H
#define INCLUDED_PA_DSOUND_DYNLINK_H
/* on Borland compilers, WIN32 doesn't seem to be defined by default, which
breaks dsound.h. Adding the define here fixes the problem. - rossb. */
#ifdef __BORLANDC__
#if !defined(WIN32)
#define WIN32
#endif
#endif
/*
Use the earliest version of DX required, no need to pollute the namespace
*/
#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
#define DIRECTSOUND_VERSION 0x0800
#else
#define DIRECTSOUND_VERSION 0x0300
#endif
#include <dsound.h>
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
typedef struct
{
HINSTANCE hInstance_;
HRESULT (WINAPI *DllGetClassObject)(REFCLSID , REFIID , LPVOID *);
HRESULT (WINAPI *DirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
HRESULT (WINAPI *DirectSoundEnumerateW)(LPDSENUMCALLBACKW, LPVOID);
HRESULT (WINAPI *DirectSoundEnumerateA)(LPDSENUMCALLBACKA, LPVOID);
HRESULT (WINAPI *DirectSoundCaptureCreate)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN);
HRESULT (WINAPI *DirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW, LPVOID);
HRESULT (WINAPI *DirectSoundCaptureEnumerateA)(LPDSENUMCALLBACKA, LPVOID);
#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
HRESULT (WINAPI *DirectSoundFullDuplexCreate8)(
LPCGUID, LPCGUID, LPCDSCBUFFERDESC, LPCDSBUFFERDESC,
HWND, DWORD, LPDIRECTSOUNDFULLDUPLEX *, LPDIRECTSOUNDCAPTUREBUFFER8 *,
LPDIRECTSOUNDBUFFER8 *, LPUNKNOWN );
#endif
}PaWinDsDSoundEntryPoints;
extern PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints;
void PaWinDs_InitializeDSoundEntryPoints(void);
void PaWinDs_TerminateDSoundEntryPoints(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* INCLUDED_PA_DSOUND_DYNLINK_H */

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more