summaryrefslogtreecommitdiff
path: root/3rdparty/portaudio/bindings/cpp/source/portaudiocpp/CppFunCallbackStream.cxx
blob: fe0b4ab0cd5686d9497ed72957a39743f7d0aee1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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);
		}
	}

	// -----------------------------------------------------------------------------------
}