Skip to content
Snippets Groups Projects
Commit 3ad59d5b authored by llea's avatar llea
Browse files

*** empty log message ***

parent ef0ed27d
Branches
Tags
No related merge requests found
Showing
with 10057 additions and 0 deletions
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 Ross Bencina <rossb@audiomulch.com>.
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
files from pa_common/ and platform specific files from pa_win/ (for Win32)
or pa_mac/ (for Macintosh).
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, possibly Mac), you may simply
be able to type:
./configure --with-host_os=mingw --with-winapi=asio [--with-asiodir=/usr/local/asiosdk2]
make
./configure --with-host_os=darwin --with-winapi=asio [--with-asiodir=/usr/local/asiosdk2]
make
and life will be good.
Obtaining the ASIO SDK
----------------------
In order to build PortAudio with ASIO support, you need to download
the ASIO SDK (version 2.0) 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/ps/support/3rdparty/asio_sdk/
If the above link is broken search Google for:
"download steinberg ASIO SDK"
Building the ASIO SDK on 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
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 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.audiomulch.com/~rossb/code/calliasio
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;
}
---
File added
File added
This diff is collapsed.
// ****************************************************************************
// 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__)
// 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 */
This diff is collapsed.
#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.
*
* 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.
*
* 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.
*
*/
/** @file
@brief ASIO-specific PortAudio API extension header file.
*/
#include "portaudio.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/** Retrieve legal latency settings for the specificed device, in samples.
@param device The global index of the device about which the query is being made.
@param minLatency A pointer to the location which will recieve the minimum latency value.
@param maxLatency A pointer to the location which will recieve the maximum latency value.
@param preferredLatency A pointer to the location which will recieve the preferred latency value.
@param granularity A pointer to the location which will recieve the granularity. This value
determines which values between minLatency and maxLatency are available. ie the step size,
if granularity is -1 then available latency settings are powers of two.
@see ASIOGetBufferSize in the ASIO SDK.
@todo This function should have a better name, any suggestions?
*/
PaError PaAsio_GetAvailableLatencyValues( PaDeviceIndex device,
long *minLatency, long *maxLatency, long *preferredLatency, long *granularity );
/** 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 );
#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 */
/*
* $Id$
* PortAudio Portable Real-Time Audio Library
* Latest Version at: http://www.portaudio.com
* BeOS Media Kit Implementation by Joshua Haberman
*
* Copyright (c) 2001 Joshua Haberman <joshua@haberman.com>
*
* 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.
*
* 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.
*
* 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.
*
* ---
*
* Significant portions of this file are based on sample code from Be. The
* Be Sample Code Licence follows:
*
* Copyright 1991-1999, Be Incorporated.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions, and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <be/media/BufferGroup.h>
#include <be/media/Buffer.h>
#include <be/media/TimeSource.h>
#include "PlaybackNode.h"
#define PRINT(x) { printf x; fflush(stdout); }
#ifdef DEBUG
#define DBUG(x) PRINT(x)
#else
#define DBUG(x)
#endif
PaPlaybackNode::PaPlaybackNode(uint32 channels, float frame_rate, uint32 frames_per_buffer,
PortAudioCallback* callback, void *user_data) :
BMediaNode("PortAudio input node"),
BBufferProducer(B_MEDIA_RAW_AUDIO),
BMediaEventLooper(),
mAborted(false),
mRunning(false),
mBufferGroup(NULL),
mDownstreamLatency(0),
mStartTime(0),
mCallback(callback),
mUserData(user_data),
mFramesPerBuffer(frames_per_buffer)
{
DBUG(("Constructor called.\n"));
mPreferredFormat.type = B_MEDIA_RAW_AUDIO;
mPreferredFormat.u.raw_audio.channel_count = channels;
mPreferredFormat.u.raw_audio.frame_rate = frame_rate;
mPreferredFormat.u.raw_audio.byte_order =
(B_HOST_IS_BENDIAN) ? B_MEDIA_BIG_ENDIAN : B_MEDIA_LITTLE_ENDIAN;
mPreferredFormat.u.raw_audio.buffer_size =
media_raw_audio_format::wildcard.buffer_size;
mOutput.destination = media_destination::null;
mOutput.format = mPreferredFormat;
/* The amount of time it takes for this node to produce a buffer when
* asked. Essentially, it is how long the user's callback takes to run.
* We set this to be the length of the sound data each buffer of the
* requested size can hold. */
//mInternalLatency = (bigtime_t)(1000000 * frames_per_buffer / frame_rate);
/* ACK! it seems that the mixer (at least on my machine) demands that IT
* specify the buffer size, so for now I'll just make a generic guess here */
mInternalLatency = 1000000 / 20;
}
PaPlaybackNode::~PaPlaybackNode()
{
DBUG(("Destructor called.\n"));
Quit(); /* Stop the BMediaEventLooper thread */
}
/*************************
*
* Local methods
*
*/
bool PaPlaybackNode::IsRunning()
{
return mRunning;
}
PaTimestamp PaPlaybackNode::GetStreamTime()
{
BTimeSource *timeSource = TimeSource();
PaTimestamp time = (timeSource->Now() - mStartTime) *
mPreferredFormat.u.raw_audio.frame_rate / 1000000;
return time;
}
void PaPlaybackNode::SetSampleFormat(PaSampleFormat inFormat,
PaSampleFormat outFormat)
{
uint32 beOutFormat;
switch(outFormat)
{
case paFloat32:
beOutFormat = media_raw_audio_format::B_AUDIO_FLOAT;
mOutputSampleWidth = 4;
break;
case paInt16:
beOutFormat = media_raw_audio_format::B_AUDIO_SHORT;
mOutputSampleWidth = 2;
break;
case paInt32:
beOutFormat = media_raw_audio_format::B_AUDIO_INT;
mOutputSampleWidth = 4;
break;
case paInt8:
beOutFormat = media_raw_audio_format::B_AUDIO_CHAR;
mOutputSampleWidth = 1;
break;
case paUInt8:
beOutFormat = media_raw_audio_format::B_AUDIO_UCHAR;
mOutputSampleWidth = 1;
break;
case paInt24:
case paPackedInt24:
case paCustomFormat:
DBUG(("Unsupported output format: %x\n", outFormat));
break;
default:
DBUG(("Unknown output format: %x\n", outFormat));
}
mPreferredFormat.u.raw_audio.format = beOutFormat;
mFramesPerBuffer * mPreferredFormat.u.raw_audio.channel_count * mOutputSampleWidth;
}
BBuffer *PaPlaybackNode::FillNextBuffer(bigtime_t time)
{
/* Get a buffer from the buffer group */
BBuffer *buf = mBufferGroup->RequestBuffer(
mOutput.format.u.raw_audio.buffer_size, BufferDuration());
unsigned long frames = mOutput.format.u.raw_audio.buffer_size /
mOutputSampleWidth / mOutput.format.u.raw_audio.channel_count;
bigtime_t start_time;
int ret;
if( !buf )
{
DBUG(("Unable to allocate a buffer\n"));
return NULL;
}
start_time = mStartTime +
(bigtime_t)((double)mSamplesSent /
(double)mOutput.format.u.raw_audio.frame_rate /
(double)mOutput.format.u.raw_audio.channel_count *
1000000.0);
/* Now call the user callback to get the data */
ret = mCallback(NULL, /* Input buffer */
buf->Data(), /* Output buffer */
frames, /* Frames per buffer */
mSamplesSent / mOutput.format.u.raw_audio.channel_count, /* timestamp */
mUserData);
if( ret )
mAborted = true;
media_header *hdr = buf->Header();
hdr->type = B_MEDIA_RAW_AUDIO;
hdr->size_used = mOutput.format.u.raw_audio.buffer_size;
hdr->time_source = TimeSource()->ID();
hdr->start_time = start_time;
return buf;
}
/*************************
*
* BMediaNode methods
*
*/
BMediaAddOn *PaPlaybackNode::AddOn( int32 * ) const
{
DBUG(("AddOn() called.\n"));
return NULL; /* we don't provide service to outside applications */
}
status_t PaPlaybackNode::HandleMessage( int32 message, const void *data,
size_t size )
{
DBUG(("HandleMessage() called.\n"));
return B_ERROR; /* we don't define any custom messages */
}
/*************************
*
* BMediaEventLooper methods
*
*/
void PaPlaybackNode::NodeRegistered()
{
DBUG(("NodeRegistered() called.\n"));
/* Start the BMediaEventLooper thread */
SetPriority(B_REAL_TIME_PRIORITY);
Run();
/* set up as much information about our output as we can */
mOutput.source.port = ControlPort();
mOutput.source.id = 0;
mOutput.node = Node();
::strcpy(mOutput.name, "PortAudio Playback");
}
void PaPlaybackNode::HandleEvent( const media_timed_event *event,
bigtime_t lateness, bool realTimeEvent )
{
// DBUG(("HandleEvent() called.\n"));
status_t err;
switch(event->type)
{
case BTimedEventQueue::B_START:
DBUG((" Handling a B_START event\n"));
if( RunState() != B_STARTED )
{
mStartTime = event->event_time + EventLatency();
mSamplesSent = 0;
mAborted = false;
mRunning = true;
media_timed_event firstEvent( mStartTime,
BTimedEventQueue::B_HANDLE_BUFFER );
EventQueue()->AddEvent( firstEvent );
}
break;
case BTimedEventQueue::B_STOP:
DBUG((" Handling a B_STOP event\n"));
mRunning = false;
EventQueue()->FlushEvents( 0, BTimedEventQueue::B_ALWAYS, true,
BTimedEventQueue::B_HANDLE_BUFFER );
break;
case BTimedEventQueue::B_HANDLE_BUFFER:
//DBUG((" Handling a B_HANDLE_BUFFER event\n"));
/* make sure we're started and connected */
if( RunState() != BMediaEventLooper::B_STARTED ||
mOutput.destination == media_destination::null )
break;
BBuffer *buffer = FillNextBuffer(event->event_time);
/* make sure we weren't aborted while this routine was running.
* this can happen in one of two ways: either the callback returned
* nonzero (in which case mAborted is set in FillNextBuffer() ) or
* the client called AbortStream */
if( mAborted )
{
if( buffer )
buffer->Recycle();
Stop(0, true);
break;
}
if( buffer )
{
err = SendBuffer(buffer, mOutput.destination);
if( err != B_OK )
buffer->Recycle();
}
mSamplesSent += mOutput.format.u.raw_audio.buffer_size / mOutputSampleWidth;
/* Now schedule the next buffer event, so we can send another
* buffer when this one runs out. We calculate when it should
* happen by calculating when the data we just sent will finish
* playing.
*
* NOTE, however, that the event will actually get generated
* earlier than we specify, to account for the latency it will
* take to produce the buffer. It uses the latency value we
* specified in SetEventLatency() to determine just how early
* to generate it. */
/* totalPerformanceTime includes the time represented by the buffer
* we just sent */
bigtime_t totalPerformanceTime = (bigtime_t)((double)mSamplesSent /
(double)mOutput.format.u.raw_audio.channel_count /
(double)mOutput.format.u.raw_audio.frame_rate * 1000000.0);
bigtime_t nextEventTime = mStartTime + totalPerformanceTime;
media_timed_event nextBufferEvent(nextEventTime,
BTimedEventQueue::B_HANDLE_BUFFER);
EventQueue()->AddEvent(nextBufferEvent);
break;
}
}
/*************************
*
* BBufferProducer methods
*
*/
status_t PaPlaybackNode::FormatSuggestionRequested( media_type type,
int32 /*quality*/, media_format* format )
{
/* the caller wants to know this node's preferred format and provides
* a suggestion, asking if we support it */
DBUG(("FormatSuggestionRequested() called.\n"));
if(!format)
return B_BAD_VALUE;
*format = mPreferredFormat;
/* we only support raw audio (a wildcard is okay too) */
if ( type == B_MEDIA_UNKNOWN_TYPE || type == B_MEDIA_RAW_AUDIO )
return B_OK;
else
return B_MEDIA_BAD_FORMAT;
}
status_t PaPlaybackNode::FormatProposal( const media_source& output,
media_format* format )
{
/* This is similar to FormatSuggestionRequested(), but it is actually part
* of the negotiation process. We're given the opportunity to specify any
* properties that are wildcards (ie. properties that the other node doesn't
* care one way or another about) */
DBUG(("FormatProposal() called.\n"));
/* Make sure this proposal really applies to our output */
if( output != mOutput.source )
return B_MEDIA_BAD_SOURCE;
/* We return two things: whether we support the proposed format, and our own
* preferred format */
*format = mPreferredFormat;
if( format->type == B_MEDIA_UNKNOWN_TYPE || format->type == B_MEDIA_RAW_AUDIO )
return B_OK;
else
return B_MEDIA_BAD_FORMAT;
}
status_t PaPlaybackNode::FormatChangeRequested( const media_source& source,
const media_destination& destination, media_format* io_format, int32* )
{
/* we refuse to change formats, supporting only 1 */
DBUG(("FormatChangeRequested() called.\n"));
return B_ERROR;
}
status_t PaPlaybackNode::GetNextOutput( int32* cookie, media_output* out_output )
{
/* this is where we allow other to enumerate our outputs -- the cookie is
* an integer we can use to keep track of where we are in enumeration. */
DBUG(("GetNextOutput() called.\n"));
if( *cookie == 0 )
{
*out_output = mOutput;
*cookie = 1;
return B_OK;
}
return B_BAD_INDEX;
}
status_t PaPlaybackNode::DisposeOutputCookie( int32 cookie )
{
DBUG(("DisposeOutputCookie() called.\n"));
return B_OK;
}
void PaPlaybackNode::LateNoticeReceived( const media_source& what,
bigtime_t how_much, bigtime_t performance_time )
{
/* This function is called as notification that a buffer we sent wasn't
* received by the time we stamped it with -- it got there late. Basically,
* it means we underestimated our own latency, so we should increase it */
DBUG(("LateNoticeReceived() called.\n"));
if( what != mOutput.source )
return;
if( RunMode() == B_INCREASE_LATENCY )
{
mInternalLatency += how_much;
SetEventLatency( mDownstreamLatency + mInternalLatency );
DBUG(("Increasing latency to %Ld\n", mDownstreamLatency + mInternalLatency));
}
else
DBUG(("I don't know what to do with this notice!"));
}
void PaPlaybackNode::EnableOutput( const media_source& what, bool enabled,
int32* )
{
DBUG(("EnableOutput() called.\n"));
/* stub -- we don't support this yet */
}
status_t PaPlaybackNode::PrepareToConnect( const media_source& what,
const media_destination& where, media_format* format,
media_source* out_source, char* out_name )
{
/* the final stage of format negotiations. here we _must_ make specific any
* remaining wildcards */
DBUG(("PrepareToConnect() called.\n"));
/* make sure this really refers to our source */
if( what != mOutput.source )
return B_MEDIA_BAD_SOURCE;
/* make sure we're not already connected */
if( mOutput.destination != media_destination::null )
return B_MEDIA_ALREADY_CONNECTED;
if( format->type != B_MEDIA_RAW_AUDIO )
return B_MEDIA_BAD_FORMAT;
if( format->u.raw_audio.format != mPreferredFormat.u.raw_audio.format )
return B_MEDIA_BAD_FORMAT;
if( format->u.raw_audio.buffer_size ==
media_raw_audio_format::wildcard.buffer_size )
{
DBUG(("We were left to decide buffer size: choosing 2048"));
format->u.raw_audio.buffer_size = 2048;
}
else
DBUG(("Using consumer specified buffer size of %lu.\n",
format->u.raw_audio.buffer_size));
/* Reserve the connection, return the information */
mOutput.destination = where;
mOutput.format = *format;
*out_source = mOutput.source;
strncpy( out_name, mOutput.name, B_MEDIA_NAME_LENGTH );
return B_OK;
}
void PaPlaybackNode::Connect(status_t error, const media_source& source,
const media_destination& destination, const media_format& format, char* io_name)
{
DBUG(("Connect() called.\n"));
/*
* $Id$
* PortAudio Portable Real-Time Audio Library
* Latest Version at: http://www.portaudio.com
* BeOS Media Kit Implementation by Joshua Haberman
*
* Copyright (c) 2001 Joshua Haberman <joshua@haberman.com>
*
* 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.
*
* 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.
*
* 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.
*
*/
#include <be/media/MediaRoster.h>
#include <be/media/MediaEventLooper.h>
#include <be/media/BufferProducer.h>
#include "portaudio.h"
class PaPlaybackNode :
public BBufferProducer,
public BMediaEventLooper
{
public:
PaPlaybackNode( uint32 channels, float frame_rate, uint32 frames_per_buffer,
PortAudioCallback *callback, void *user_data );
~PaPlaybackNode();
/* Local methods ******************************************/
BBuffer *FillNextBuffer(bigtime_t time);
void SetSampleFormat(PaSampleFormat inFormat, PaSampleFormat outFormat);
bool IsRunning();
PaTimestamp GetStreamTime();
/* BMediaNode methods *************************************/
BMediaAddOn* AddOn( int32 * ) const;
status_t HandleMessage( int32 message, const void *data, size_t size );
/* BMediaEventLooper methods ******************************/
void HandleEvent( const media_timed_event *event, bigtime_t lateness,
bool realTimeEvent );
void NodeRegistered();
/* BBufferProducer methods ********************************/
status_t FormatSuggestionRequested( media_type type, int32 quality,
media_format* format );
status_t FormatProposal( const media_source& output, media_format* format );
status_t FormatChangeRequested( const media_source& source,
const media_destination& destination, media_format* io_format, int32* );
status_t GetNextOutput( int32* cookie, media_output* out_output );
status_t DisposeOutputCookie( int32 cookie );
void LateNoticeReceived( const media_source& what, bigtime_t how_much,
bigtime_t performance_time );
void EnableOutput( const media_source& what, bool enabled, int32* _deprecated_ );
status_t PrepareToConnect( const media_source& what,
const media_destination& where, media_format* format,
media_source* out_source, char* out_name );
void Connect(status_t error, const media_source& source,
const media_destination& destination, const media_format& format,
char* io_name);
void Disconnect(const media_source& what, const media_destination& where);
status_t SetBufferGroup(const media_source& for_source, BBufferGroup* newGroup);
bool mAborted;
private:
media_output mOutput;
media_format mPreferredFormat;
uint32 mOutputSampleWidth, mFramesPerBuffer;
BBufferGroup *mBufferGroup;
bigtime_t mDownstreamLatency, mInternalLatency, mStartTime;
uint64 mSamplesSent;
PortAudioCallback *mCallback;
void *mUserData;
bool mRunning;
};
This diff is collapsed.
/*
* $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.
*
* 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.
*
* 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.
*/
/** @file
@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;
}
}
#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-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.
*
* 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.
*
* 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.
*/
/** @file
@brief Allocation Group prototypes. An Allocation Group makes it easy to
allocate multiple blocks of memory and free them all simultanously.
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 deallocate them all simultaneously which
can be usefull 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 */
This diff is collapsed.
This diff is collapsed.
/*
* $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.
*
* 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.
*
* 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.
*/
/** @file
@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.
*/
#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 */
#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;
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment