⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pa_asio.cpp

📁 mediastreamer2是开源的网络传输媒体流的库
💻 CPP
📖 第 1 页 / 共 5 页
字号:
/* * $Id: pa_asio.cpp 1067 2006-07-07 13:25:04Z davidv $ * Portable Audio I/O Library for ASIO Drivers * * Author: Stephane Letz * Based on the Open Source API proposed by Ross Bencina * Copyright (c) 2000-2002 Stephane Letz, 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. * * 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. *//* Modification History        08-03-01 First version : Stephane Letz        08-06-01 Tweaks for PC, use C++, buffer allocation, Float32 to Int32 conversion : Phil Burk        08-20-01 More conversion, PA_StreamTime, Pa_GetHostError : Stephane Letz        08-21-01 PaUInt8 bug correction, implementation of ASIOSTFloat32LSB and ASIOSTFloat32MSB native formats : Stephane Letz        08-24-01 MAX_INT32_FP hack, another Uint8 fix : Stephane and Phil        08-27-01 Implementation of hostBufferSize < userBufferSize case, better management of the ouput buffer when                 the stream is stopped : Stephane Letz        08-28-01 Check the stream pointer for null in bufferSwitchTimeInfo, correct bug in bufferSwitchTimeInfo when                 the stream is stopped : Stephane Letz        10-12-01 Correct the PaHost_CalcNumHostBuffers function: computes FramesPerHostBuffer to be the lowest that                 respect requested FramesPerUserBuffer and userBuffersPerHostBuffer : Stephane Letz        10-26-01 Management of hostBufferSize and userBufferSize of any size : Stephane Letz        10-27-01 Improve calculus of hostBufferSize to be multiple or divisor of userBufferSize if possible : Stephane and Phil        10-29-01 Change MAX_INT32_FP to (2147483520.0f) to prevent roundup to 0x80000000 : Phil Burk        10-31-01 Clear the ouput buffer and user buffers in PaHost_StartOutput, correct bug in GetFirstMultiple : Stephane Letz        11-06-01 Rename functions : Stephane Letz        11-08-01 New Pa_ASIO_Adaptor_Init function to init Callback adpatation variables, cleanup of Pa_ASIO_Callback_Input: Stephane Letz        11-29-01 Break apart device loading to debug random failure in Pa_ASIO_QueryDeviceInfo ; Phil Burk        01-03-02 Desallocate all resources in PaHost_Term for cases where Pa_CloseStream is not called properly :  Stephane Letz        02-01-02 Cleanup, test of multiple-stream opening : Stephane Letz        19-02-02 New Pa_ASIO_loadDriver that calls CoInitialize on each thread on Windows : Stephane Letz        09-04-02 Correct error code management in PaHost_Term, removes various compiler warning : Stephane Letz        12-04-02 Add Mac includes for <Devices.h> and <Timer.h> : Phil Burk        13-04-02 Removes another compiler warning : Stephane Letz        30-04-02 Pa_ASIO_QueryDeviceInfo bug correction, memory allocation checking, better error handling : D Viens, P Burk, S Letz        12-06-02 Rehashed into new multi-api infrastructure, added support for all ASIO sample formats : Ross Bencina        18-06-02 Added pa_asio.h, PaAsio_GetAvailableLatencyValues() : Ross B.        21-06-02 Added SelectHostBufferSize() which selects host buffer size based on user latency parameters : Ross Bencina        ** NOTE  maintanance history is now stored in CVS ***//** @file    Note that specific support for paInputUnderflow, paOutputOverflow and    paNeverDropInput is not necessary or possible with this driver due to the    synchronous full duplex double-buffered architecture of ASIO.    @todo check that CoInitialize()/CoUninitialize() are always correctly        paired, even in error cases.    @todo implement host api specific extension to set i/o buffer sizes in frames    @todo implement ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable    @todo implement IsFormatSupported    @todo work out how to implement stream stoppage from callback and            implement IsStreamActive properly. Stream stoppage could be implemented            using a high-priority thread blocked on an Event which is signalled            by the callback. Or, we could just call ASIO stop from the callback            and see what happens.    @todo rigorously check asio return codes and convert to pa error codes    @todo Different channels of a multichannel stream can have different sample            formats, but we assume that all are the same as the first channel for now.            Fixing this will require the block processor to maintain per-channel            conversion functions - could get nasty.    @todo investigate whether the asio processNow flag needs to be honoured    @todo handle asioMessages() callbacks in a useful way, or at least document            what cases we don't handle.    @todo miscellaneous other FIXMEs    @todo provide an asio-specific method for setting the systems specific        value (aka main window handle) - check that this matches the value        passed to PaAsio_ShowControlPanel, or remove it entirely from        PaAsio_ShowControlPanel. - this would allow PaAsio_ShowControlPanel        to be called for the currently open stream (at present all streams        must be closed).*/#include <stdio.h>#include <assert.h>#include <string.h>//#include <values.h>#include <windows.h>#include <mmsystem.h>#include "portaudio.h"#include "pa_asio.h"#include "pa_util.h"#include "pa_allocation.h"#include "pa_hostapi.h"#include "pa_stream.h"#include "pa_cpuload.h"#include "pa_process.h"/* This version of pa_asio.cpp is currently only targetted at Win32,   It would require a few tweaks to work with pre-OS X Macintosh.   To make configuration easier, we define WIN32 here to make sure   that the ASIO SDK knows this is Win32.*/#ifndef WIN32#define WIN32#endif#include "asiosys.h"#include "asio.h"#include "asiodrivers.h"#include "iasiothiscallresolver.h"/*#if MAC#include <Devices.h>#include <Timer.h>#include <Math64.h>#else*//*#include <math.h>#include <windows.h>#include <mmsystem.h>*//*#endif*//* external references */extern AsioDrivers* asioDrivers ;bool loadAsioDriver(char *name);/* We are trying to be compatible with CARBON but this has not been thoroughly tested. *//* not tested at all since new code was introduced. */#define CARBON_COMPATIBLE  (0)/* prototypes for functions declared in this file */extern "C" PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex );static void Terminate( struct PaUtilHostApiRepresentation *hostApi );static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,                           PaStream** s,                           const PaStreamParameters *inputParameters,                           const PaStreamParameters *outputParameters,                           double sampleRate,                           unsigned long framesPerBuffer,                           PaStreamFlags streamFlags,                           PaStreamCallback *streamCallback,                           void *userData );static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,                                  const PaStreamParameters *inputParameters,                                  const PaStreamParameters *outputParameters,                                  double sampleRate );static PaError CloseStream( PaStream* stream );static PaError StartStream( PaStream *stream );static PaError StopStream( PaStream *stream );static PaError AbortStream( PaStream *stream );static PaError IsStreamStopped( PaStream *s );static PaError IsStreamActive( PaStream *stream );static PaTime GetStreamTime( PaStream *stream );static double GetStreamCpuLoad( PaStream* stream );static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );static signed long GetStreamReadAvailable( PaStream* stream );static signed long GetStreamWriteAvailable( PaStream* stream );/* our ASIO callback functions */static void bufferSwitch(long index, ASIOBool processNow);static ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow);static void sampleRateChanged(ASIOSampleRate sRate);static long asioMessages(long selector, long value, void* message, double* opt);static ASIOCallbacks asioCallbacks_ =    { bufferSwitch, sampleRateChanged, asioMessages, bufferSwitchTimeInfo };#define PA_ASIO_SET_LAST_HOST_ERROR( errorCode, errorText ) \    PaUtil_SetLastHostErrorInfo( paASIO, errorCode, errorText )static void PaAsio_SetLastSystemError( DWORD errorCode ){    LPVOID lpMsgBuf;    FormatMessage(        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,        NULL,        errorCode,        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),        (LPTSTR) &lpMsgBuf,        0,        NULL    );    PaUtil_SetLastHostErrorInfo( paASIO, errorCode, (const char*)lpMsgBuf );    LocalFree( lpMsgBuf );}#define PA_ASIO_SET_LAST_SYSTEM_ERROR( errorCode ) \    PaAsio_SetLastSystemError( errorCode )static const char* PaAsio_GetAsioErrorText( ASIOError asioError ){    const char *result;    switch( asioError ){        case ASE_OK:        case ASE_SUCCESS:           result = "Success"; break;        case ASE_NotPresent:        result = "Hardware input or output is not present or available"; break;        case ASE_HWMalfunction:     result = "Hardware is malfunctioning"; break;        case ASE_InvalidParameter:  result = "Input parameter invalid"; break;        case ASE_InvalidMode:       result = "Hardware is in a bad mode or used in a bad mode"; break;        case ASE_SPNotAdvancing:    result = "Hardware is not running when sample position is inquired"; break;        case ASE_NoClock:           result = "Sample clock or rate cannot be determined or is not present"; break;        case ASE_NoMemory:          result = "Not enough memory for completing the request"; break;        default:                    result = "Unknown ASIO error"; break;    }    return result;}#define PA_ASIO_SET_LAST_ASIO_ERROR( asioError ) \    PaUtil_SetLastHostErrorInfo( paASIO, asioError, PaAsio_GetAsioErrorText( asioError ) )// Atomic increment and decrement operations#if MAC	/* need to be implemented on Mac */	inline long PaAsio_AtomicIncrement(volatile long* v) {return ++(*const_cast<long*>(v));}	inline long PaAsio_AtomicDecrement(volatile long* v) {return --(*const_cast<long*>(v));}#elif WINDOWS	inline long PaAsio_AtomicIncrement(volatile long* v) {return InterlockedIncrement(const_cast<long*>(v));}	inline long PaAsio_AtomicDecrement(volatile long* v) {return InterlockedDecrement(const_cast<long*>(v));}#endiftypedef struct PaAsioDriverInfo{    ASIODriverInfo asioDriverInfo;    long inputChannelCount, outputChannelCount;    long bufferMinSize, bufferMaxSize, bufferPreferredSize, bufferGranularity;    bool postOutput;}PaAsioDriverInfo;/* PaAsioHostApiRepresentation - host api datastructure specific to this implementation */typedef struct{    PaUtilHostApiRepresentation inheritedHostApiRep;    PaUtilStreamInterface callbackStreamInterface;    PaUtilStreamInterface blockingStreamInterface;    PaUtilAllocationGroup *allocations;    void *systemSpecific;        /* the ASIO C API only allows one ASIO driver to be open at a time,        so we keep track of whether we have the driver open here, and        use this information to return errors from OpenStream if the        driver is already open.        openAsioDeviceIndex will be PaNoDevice if there is no device open        and a valid pa_asio (not global) device index otherwise.        openAsioDriverInfo is populated with the driver info for the        currently open device (if any)    */    PaDeviceIndex openAsioDeviceIndex;    PaAsioDriverInfo openAsioDriverInfo;}PaAsioHostApiRepresentation;/*    Retrieve <driverCount> driver names from ASIO, returned in a char**    allocated in <group>.*/static char **GetAsioDriverNames( PaUtilAllocationGroup *group, long driverCount ){    char **result = 0;    int i;    result =(char**)PaUtil_GroupAllocateMemory(            group, sizeof(char*) * driverCount );    if( !result )        goto error;    result[0] = (char*)PaUtil_GroupAllocateMemory(            group, 32 * driverCount );    if( !result[0] )        goto error;    for( i=0; i<driverCount; ++i )        result[i] = result[0] + (32 * i);    asioDrivers->getDriverNames( result, driverCount );error:    return result;}static PaSampleFormat AsioSampleTypeToPaNativeSampleFormat(ASIOSampleType type){    switch (type) {        case ASIOSTInt16MSB:        case ASIOSTInt16LSB:                return paInt16;        case ASIOSTFloat32MSB:        case ASIOSTFloat32LSB:        case ASIOSTFloat64MSB:        case ASIOSTFloat64LSB:                return paFloat32;        case ASIOSTInt32MSB:        case ASIOSTInt32LSB:        case ASIOSTInt32MSB16:        case ASIOSTInt32LSB16:        case ASIOSTInt32MSB18:        case ASIOSTInt32MSB20:        case ASIOSTInt32MSB24:        case ASIOSTInt32LSB18:        case ASIOSTInt32LSB20:        case ASIOSTInt32LSB24:                return paInt32;        case ASIOSTInt24MSB:        case ASIOSTInt24LSB:                return paInt24;        default:                return paCustomFormat;    }}void AsioSampleTypeLOG(ASIOSampleType type)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -