summaryrefslogtreecommitdiff
path: root/libs/backends/wavesaudio/wavesapi/devicemanager/WCMRNativeAudio.cpp
blob: 0bce97423caf997e7c97da1ff90f23ac0f1a7ac9 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//----------------------------------------------------------------------------------
//
// Copyright (c) 2008 Waves Audio Ltd. All rights reserved.
//
//! \file	WCMRNativeAudio.cpp
//!
//! WCMRNativeAudioConnection and related class defienitions
//!
//---------------------------------------------------------------------------------*/
#if defined(__APPLE__)
#include <CoreAudio/CoreAudio.h>
#endif

#include "WCMRNativeAudio.h"
#include "MiscUtils/pthread_utils.h"
#include "MiscUtils/safe_delete.h"
#include <iostream>
#include <sstream>
#include <boost/assign/list_of.hpp>

#define NONE_DEVICE_NAME "None"
#define NONE_DEVICE_INPUT_NAMES "Input "
#define NONE_DEVICE_OUTPUT_NAMES "Output "

//**********************************************************************************************
// WCMRNativeAudioNoneDevice::WCMRNativeAudioNoneDevice
//
//! Constructor for the dummy "None" device. This constructor simply adds supported SRs,
//!		buffer sizes, and channels, so that it may look like a real native device to
//!		the applications.
//!
//! \param pManager : The managing device manager - simply passed on to the base class.
//!
//!
//**********************************************************************************************
WCMRNativeAudioNoneDevice::WCMRNativeAudioNoneDevice (WCMRAudioDeviceManager *pManager)
	: WCMRNativeAudioDevice (pManager, false /*useMultiThreading*/)
#ifndef PTW32_VERSION
	, m_SilenceThread(0)
#endif
#if defined (PLATFORM_WINDOWS)
    , _waitableTimerForUsleep (CreateWaitableTimer(NULL, TRUE, NULL))
#endif
{
	mark_pthread_inactive (m_SilenceThread);

	m_DeviceName = NONE_DEVICE_NAME;

	m_SamplingRates = boost::assign::list_of (m_CurrentSamplingRate=44100)(48000)(88200)(96000)(176400)(192000);

	m_BufferSizes = boost::assign::list_of (32)(64)(128)(m_CurrentBufferSize=256)(512)(1024);

	for (int channel = 0; channel < __m_NumInputChannels; channel++)
	{
        std::stringstream name;
        name << NONE_DEVICE_INPUT_NAMES;
		name << (channel + 1);
		m_InputChannels.push_back(name.str());
	}

	for (int channel = 0; channel < __m_NumOutputChannels; channel++)
	{
        std::stringstream name;
        name << NONE_DEVICE_INPUT_NAMES;
		name << (channel + 1);
		m_OutputChannels.push_back(name.str());
	}
	_m_inputBuffer = new float[__m_NumInputChannels * m_BufferSizes.back()];
	_m_outputBuffer = new float[__m_NumOutputChannels * m_BufferSizes.back()];
	m_CurrentBufferSize = m_BufferSizes.back();
}


WCMRNativeAudioNoneDevice::~WCMRNativeAudioNoneDevice ()
{
#if defined (PLATFORM_WINDOWS)
    if(_waitableTimerForUsleep) {
        CloseHandle(_waitableTimerForUsleep);
    }
#endif
}

WTErr WCMRNativeAudioNoneDevice::SetActive (bool newState)
{
	//This will most likely be overridden, the base class simply
	//changes the member.
	if (Active() == newState)
	{
		return (eNoErr);
	}

	if (Active() && Streaming())
	{
		SetStreaming(false);
	}
	return WCMRAudioDevice::SetActive(newState);
}

WTErr WCMRNativeAudioNoneDevice::SetCurrentBufferSize (int newSize)
{

	//changes the status.
	int oldSize = CurrentBufferSize();
	bool oldActive = Active();

	//same size, nothing to do.
	if (oldSize == newSize)
		return eNoErr;
	
	//see if this is one of our supported rates...
	std::vector<int>::iterator intIter = find(m_BufferSizes.begin(), m_BufferSizes.end(), newSize);
	if (intIter == m_BufferSizes.end())
	{
		//Can't change, perhaps use an "invalid param" type of error
		return eCommandLineParameter;
	}
	
	if (Streaming())
	{
		//Can't change, perhaps use an "in use" type of error
		return eGenericErr;
	}

	
	return WCMRAudioDevice::SetCurrentBufferSize(newSize);
}


WTErr WCMRNativeAudioNoneDevice::UpdateDeviceInfo ()
{
	return eNoErr;
}


WTErr WCMRNativeAudioNoneDevice::SetStreaming (bool newState)
{
	if (Streaming() == newState)
	{
		return (eNoErr);
	}

	WCMRAudioDevice::SetStreaming(newState);

	if (Streaming())
	{
		if (is_pthread_active (m_SilenceThread))
			std::cerr << "\t\t\t\t\t !!!!!!!!!!!!!!! Warning: the inactive NONE-DEVICE was streaming!" << std::endl;

		pthread_attr_t attributes;
		size_t stack_size = 100000;
#ifdef __APPLE__
	    stack_size = (((stack_size - 1) / PTHREAD_STACK_MIN) + 1) * PTHREAD_STACK_MIN;
#endif
		if (pthread_attr_init (&attributes)) {
			std::cerr << "WCMRNativeAudioNoneDevice::SetStreaming (): pthread_attr_init () failed!" << std::endl;
			return eGenericErr;
		}

		if (pthread_attr_setstacksize (&attributes, stack_size)) {
			std::cerr << "WCMRNativeAudioNoneDevice::SetStreaming (): pthread_attr_setstacksize () failed!" << std::endl;
			return eGenericErr;
		}

		if (pthread_create (&m_SilenceThread, &attributes, __SilenceThread, this)) {
			mark_pthread_inactive (m_SilenceThread);
			std::cerr << "WCMRNativeAudioNoneDevice::SetStreaming (): pthread_create () failed!" << std::endl;
			return eGenericErr;
		}
	}
	else
	{
		if (!is_pthread_active (m_SilenceThread))
		{
			std::cerr << "\t\t\t\t\t !!!!!!!!!!!!!!! Warning: the active NONE-DEVICE was NOT streaming!" << std::endl;
		}

		while (is_pthread_active (m_SilenceThread))
		{
			_usleep(1); //now wait for ended  thread;
		}
	}

	return eNoErr;
}

void WCMRNativeAudioNoneDevice::_SilenceThread()
{
#if defined(PLATFORM_WINDOWS)
	float* theInpBuffers[__m_NumInputChannels];
	for(int i = 0; i < __m_NumInputChannels; ++i)
	{
		theInpBuffers[i] = _m_inputBuffer + m_BufferSizes.back() * i;
	}
#else
	float* theInpBuffers = _m_inputBuffer;
#endif

	const size_t buffer_size = CurrentBufferSize();
    const uint64_t cyclePeriodNanos = (1000000000.0 * buffer_size) / CurrentSamplingRate();

	struct WCMRAudioDeviceManagerClient::AudioCallbackData audioCallbackData =
	{
		(const float*)theInpBuffers,
		_m_outputBuffer,
		buffer_size,
		0,
		0
	};

	audioCallbackData.acdCycleStartTimeNanos =__get_time_nanos();

    // VERY ROUGH IMPLEMENTATION:
    while(Streaming()) {
	
        uint64_t cycleEndTimeNanos = audioCallbackData.acdCycleStartTimeNanos + cyclePeriodNanos;

		m_pMyManager->NotifyClient (WCMRAudioDeviceManagerClient::AudioCallback, (void *)&audioCallbackData);
		
        audioCallbackData.acdSampleTime += buffer_size;
		
		int64_t timeToSleepUsecs = ((int64_t)cycleEndTimeNanos - (int64_t)__get_time_nanos())/1000;
		
        if (timeToSleepUsecs > 0) {
            _usleep (timeToSleepUsecs);
        }
		audioCallbackData.acdCycleStartTimeNanos = cycleEndTimeNanos+1;
    }
	mark_pthread_inactive (m_SilenceThread);
}

void* WCMRNativeAudioNoneDevice::__SilenceThread(void *This)
{
	((WCMRNativeAudioNoneDevice*)This)->_SilenceThread();
	return 0;
}

#if defined(PLATFORM_WINDOWS)
void WCMRNativeAudioNoneDevice::_usleep(uint64_t duration_usec)
{
    LARGE_INTEGER ft;

    ft.QuadPart = -(10*duration_usec); // Convert to 100 nanosecond interval, negative value indicates relative time

    SetWaitableTimer(_waitableTimerForUsleep, &ft, 0, NULL, NULL, 0);
    WaitForSingleObject(_waitableTimerForUsleep, INFINITE);
}
#endif

uint64_t
WCMRNativeAudioNoneDevice::__get_time_nanos ()
{
#ifdef __APPLE__
    // here we exploit the time counting API which is used by the WCMRCoreAudioDeviceManager. However,
    // the API should be a part of WCMRCoreAudioDeviceManager to give a chance of being tied to the
    // audio device transport timeß.
    return AudioConvertHostTimeToNanos (AudioGetCurrentHostTime ());

#elif PLATFORM_WINDOWS

    LARGE_INTEGER Frequency, Count ;

    QueryPerformanceFrequency (&Frequency) ;
    QueryPerformanceCounter (&Count);
    return uint64_t ((Count.QuadPart * 1000000000.0 / Frequency.QuadPart));
#endif
}