| 6 |
| 7 |
| 8 | #include <assert.h> |
| 9 | #include "AudioInputWASAPI.h" |
| 10 | #include "../../logging.h" |
| 11 | #include "../../VoIPController.h" |
| 12 |
| 13 | #define BUFFER_SIZE 960 |
| 14 | #define CHECK_RES(res, msg) {if(FAILED(res)){LOGE("%s failed: HRESULT=0x%08X", msg, res); failed=true; return;}} |
| 15 | #define SCHECK_RES(res, msg) {if(FAILED(res)){LOGE("%s failed: HRESULT=0x%08X", msg, res); return;}} |
| 16 |
| 17 | template <class T> void SafeRelease(T **ppT) |
| 18 | { |
| 19 | if(*ppT) |
| 20 | { |
| 21 | (*ppT)->Release(); |
| 22 | *ppT = NULL; |
| 23 | } |
| 24 | } |
| 25 |
| 26 | using namespace tgvoip::audio; |
| 27 |
| 28 | AudioInputWASAPI::AudioInputWASAPI(std::string deviceID){ |
| 29 | isRecording=false; |
| 30 | remainingDataLen=0; |
| 31 | refCount=1; |
| 32 | HRESULT res; |
| 33 | res=CoInitializeEx(NULL, COINIT_MULTITHREADED); |
| 34 | if(FAILED(res) && res!=RPC_E_CHANGED_MODE){ |
| 35 | CHECK_RES(res, "CoInitializeEx"); |
| 36 | } |
| 37 | #ifdef TGVOIP_WINXP_COMPAT |
| 38 | HANDLE (WINAPI *__CreateEventExA)(LPSECURITY_ATTRIBUTES lpEventAttributes, LPCSTR lpName, DWORD dwFlags, DWORD dwDesiredAccess); |
| 39 | __CreateEventExA=(HANDLE (WINAPI *)(LPSECURITY_ATTRIBUTES, LPCSTR, DWORD, DWORD))GetProcAddress(GetModuleHandleA("kernel32.dll"), "CreateEventExA"); |
| 40 | #undef CreateEventEx |
| 41 | #define CreateEventEx __CreateEventExA |
| 42 | #endif |
| 43 | shutdownEvent=CreateEventEx(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE); |
| 44 | audioSamplesReadyEvent=CreateEventEx(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE); |
| 45 | streamSwitchEvent=CreateEventEx(NULL, NULL, 0, EVENT_MODIFY_STATE | SYNCHRONIZE); |
| 46 | ZeroMemory(&format, sizeof(format)); |
| 47 | format.wFormatTag=WAVE_FORMAT_PCM; |
| 48 | format.nChannels=1; |
| 49 | format.nSamplesPerSec=48000; |
| 50 | format.nBlockAlign=2; |
| 51 | format.nAvgBytesPerSec=format.nSamplesPerSec*format.nBlockAlign; |
| 52 | format.wBitsPerSample=16; |
| 53 |
| 54 | #ifdef TGVOIP_WINDOWS_DESKTOP |
| 55 | res=CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&enumerator)); |
| 56 | CHECK_RES(res, "CoCreateInstance(MMDeviceEnumerator)"); |
| 57 | res=enumerator->RegisterEndpointNotificationCallback(this); |
| 58 | CHECK_RES(res, "enumerator->RegisterEndpointNotificationCallback"); |
| 59 | audioSessionControl=NULL; |
| 60 | device=NULL; |
| 61 | #endif |
| 62 |
| 63 | audioClient=NULL; |
| 64 | captureClient=NULL; |
| 65 | thread=NULL; |
| 66 | started=false; |
| 67 |
| 68 | SetCurrentDevice(deviceID); |
| 69 | } |
| 70 |
| 71 | AudioInputWASAPI::~AudioInputWASAPI(){ |
| 72 | if(audioClient && started){ |
| 73 | audioClient->Stop(); |
| 74 | } |
| 75 |
| 76 | #ifdef TGVOIP_WINDOWS_DESKTOP |
| 77 | if(audioSessionControl){ |
| 78 | audioSessionControl->UnregisterAudioSessionNotification(this); |
| 79 | } |
| 80 | #endif |
| 81 |
| 82 | SetEvent(shutdownEvent); |
| 83 | if(thread){ |
| 84 | WaitForSingleObjectEx(thread, INFINITE, false); |
| 85 | CloseHandle(thread); |
| 86 | } |
| 87 | #ifdef TGVOIP_WINDOWS_DESKTOP |
| 88 | SafeRelease(&audioSessionControl); |
| 89 | #endif |
| 90 | SafeRelease(&captureClient); |
| 91 | SafeRelease(&audioClient); |
| 92 | #ifdef TGVOIP_WINDOWS_DESKTOP |
| 93 | SafeRelease(&device); |
| 94 | #endif |
| 95 | CloseHandle(shutdownEvent); |
| 96 | CloseHandle(audioSamplesReadyEvent); |
| 97 | CloseHandle(streamSwitchEvent); |
| 98 | #ifdef TGVOIP_WINDOWS_DESKTOP |
| 99 | if(enumerator) |
| 100 | enumerator->UnregisterEndpointNotificationCallback(this); |
| 101 | SafeRelease(&enumerator); |
| 102 | #endif |
| 103 | } |
| 104 | void AudioInputWASAPI::Start(){ |
| 105 | isRecording=true; |
| 106 | if(!thread){ |
| 107 | thread=CreateThread(NULL, 0, AudioInputWASAPI::StartThread, this, 0, NULL); |
| 108 | } |
| 109 |
| 110 | if(audioClient && !started){ |
| 111 | LOGI("audioClient->Start"); |
| 112 | audioClient->Start(); |
| 113 | started=true; |
| 114 | } |
| 115 | } |
| 116 |
| 117 | void AudioInputWASAPI::Stop(){ |
| 118 | isRecording=false; |
| 119 | } |
| 120 |
| 121 | bool AudioInputWASAPI::IsRecording(){ |
| 122 | return isRecording; |
| 123 | } |
| 124 |
| 125 | void AudioInputWASAPI::EnumerateDevices(std::vector<tgvoip::AudioInputDevice>& devs){ |
| 126 | #ifdef TGVOIP_WINDOWS_DESKTOP |
| 127 | HRESULT res; |
| 128 | res=CoInitializeEx(NULL, COINIT_MULTITHREADED); |
| 129 | if(FAILED(res) && res!=RPC_E_CHANGED_MODE){ |
| 130 | SCHECK_RES(res, "CoInitializeEx"); |
| 131 | } |
| 132 |
| 133 | IMMDeviceEnumerator *deviceEnumerator = NULL; |
| 134 | IMMDeviceCollection *deviceCollection = NULL; |
| 135 |
| 136 | res=CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&deviceEnumerator)); |
| 137 | SCHECK_RES(res, "CoCreateInstance(MMDeviceEnumerator)"); |
| 138 |
| 139 | res=deviceEnumerator->EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE, &deviceCollection); |
| 140 | SCHECK_RES(res, "EnumAudioEndpoints"); |
| 141 |
| 142 | UINT devCount; |
| 143 | res=deviceCollection->GetCount(&devCount); |
| 144 | SCHECK_RES(res, "GetCount"); |
| 145 |
| 146 | for(UINT i=0;i<devCount;i++){ |
| 147 | IMMDevice* device; |
| 148 | res=deviceCollection->Item(i, &device); |
| 149 | SCHECK_RES(res, "GetDeviceItem"); |
| 150 | wchar_t* devID; |
| 151 | res=device->GetId(&devID); |
| 152 | SCHECK_RES(res, "get device id"); |
| 153 |
| 154 | IPropertyStore* propStore; |
| 155 | res=device->OpenPropertyStore(STGM_READ, &propStore); |
| 156 | SafeRelease(&device); |
| 157 | SCHECK_RES(res, "OpenPropertyStore"); |
| 158 |
| 159 | PROPVARIANT friendlyName; |
| 160 | PropVariantInit(&friendlyName); |
| 161 | res=propStore->GetValue(PKEY_Device_FriendlyName, &friendlyName); |
| 162 | SafeRelease(&propStore); |
| 163 |
| 164 | AudioInputDevice dev; |
| 165 |
| 166 | wchar_t actualFriendlyName[128]; |
| 167 | if(friendlyName.vt==VT_LPWSTR){ |
| 168 | wcsncpy(actualFriendlyName, friendlyName.pwszVal, sizeof(actualFriendlyName)/sizeof(wchar_t)); |
| 169 | }else{ |
| 170 | wcscpy(actualFriendlyName, L"Unknown"); |
| 171 | } |
| 172 | PropVariantClear(&friendlyName); |
| 173 |
| 174 | char buf[256]; |
| 175 | WideCharToMultiByte(CP_UTF8, 0, devID, -1, buf, sizeof(buf), NULL, NULL); |
| 176 | dev.id=buf; |
| 177 | WideCharToMultiByte(CP_UTF8, 0, actualFriendlyName, -1, buf, sizeof(buf), NULL, NULL); |
| 178 | dev.displayName=buf; |
| 179 | devs.push_back(dev); |
| 180 |
| 181 | CoTaskMemFree(devID); |
| 182 | } |
| 183 |
| 184 | SafeRelease(&deviceCollection); |
| 185 | SafeRelease(&deviceEnumerator); |
| 186 | #endif |
| 187 | } |
| 188 |
| 189 | void AudioInputWASAPI::SetCurrentDevice(std::string deviceID){ |
| 190 | if(thread){ |
| 191 | streamChangeToDevice=deviceID; |
| 192 | SetEvent(streamSwitchEvent); |
| 193 | }else{ |
| 194 | ActuallySetCurrentDevice(deviceID); |
| 195 | } |
| 196 | } |
| 197 |
| 198 | void AudioInputWASAPI::ActuallySetCurrentDevice(std::string deviceID){ |
| 199 | currentDevice=deviceID; |
| 200 | HRESULT res; |
| 201 |
| 202 | if(audioClient){ |
| 203 | res=audioClient->Stop(); |
| 204 | CHECK_RES(res, "audioClient->Stop"); |
| 205 | } |
| 206 |
| 207 | #ifdef TGVOIP_WINDOWS_DESKTOP |
| 208 | if(audioSessionControl){ |
| 209 | res=audioSessionControl->UnregisterAudioSessionNotification(this); |
| 210 | CHECK_RES(res, "audioSessionControl->UnregisterAudioSessionNotification"); |
| 211 | } |
| 212 |
| 213 | SafeRelease(&audioSessionControl); |
| 214 | #endif |
| 215 | SafeRelease(&captureClient); |
| 216 | SafeRelease(&audioClient); |
| 217 | #ifdef TGVOIP_WINDOWS_DESKTOP |
| 218 | SafeRelease(&device); |
| 219 |
| 220 | IMMDeviceCollection *deviceCollection = NULL; |
| 221 |
| 222 | if(deviceID=="default"){ |
| 223 | isDefaultDevice=true; |
| 224 | res=enumerator->GetDefaultAudioEndpoint(eCapture, eCommunications, &device); |
| 225 | CHECK_RES(res, "GetDefaultAudioEndpoint"); |
| 226 | }else{ |
| 227 | isDefaultDevice=false; |
| 228 | res=enumerator->EnumAudioEndpoints(eCapture, DEVICE_STATE_ACTIVE, &deviceCollection); |
| 229 | CHECK_RES(res, "EnumAudioEndpoints"); |
| 230 |
| 231 | UINT devCount; |
| 232 | res=deviceCollection->GetCount(&devCount); |
| 233 | CHECK_RES(res, "GetCount"); |
| 234 |
| 235 | for(UINT i=0;i<devCount;i++){ |
| 236 | IMMDevice* device; |
| 237 | res=deviceCollection->Item(i, &device); |
| 238 | CHECK_RES(res, "GetDeviceItem"); |
| 239 | wchar_t* _devID; |
| 240 | res=device->GetId(&_devID); |
| 241 | CHECK_RES(res, "get device id"); |
| 242 |
| 243 | char devID[128]; |
| 244 | WideCharToMultiByte(CP_UTF8, 0, _devID, -1, devID, 128, NULL, NULL); |
| 245 |
| 246 | CoTaskMemFree(_devID); |
| 247 | if(deviceID==devID){ |
| 248 | this->device=device; |
| 249 | //device->AddRef(); |
| 250 | break; |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 |
| 255 | if(deviceCollection) |
| 256 | SafeRelease(&deviceCollection); |
| 257 |
| 258 | if(!device){ |
| 259 | LOGE("Didn't find capture device; failing"); |
| 260 | failed=true; |
| 261 | return; |
| 262 | } |
| 263 |
| 264 | res=device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, (void**)&audioClient); |
| 265 | CHECK_RES(res, "device->Activate"); |
| 266 | #else |
| 267 | std::wstring devID; |
| 268 |
| 269 | if (deviceID=="default"){ |
| 270 | Platform::String^ defaultDevID=Windows::Media::Devices::MediaDevice::GetDefaultAudioCaptureId(Windows::Media::Devices::AudioDeviceRole::Communications); |
| 271 | if(defaultDevID==nullptr){ |
| 272 | LOGE("Didn't find capture device; failing"); |
| 273 | failed=true; |
| 274 | return; |
| 275 | }else{ |
| 276 | isDefaultDevice=true; |
| 277 | devID=defaultDevID->Data(); |
| 278 | } |
| 279 | }else{ |
| 280 | int wchars_num=MultiByteToWideChar(CP_UTF8, 0, deviceID.c_str(), -1, NULL, 0); |
| 281 | wchar_t* wstr=new wchar_t[wchars_num]; |
| 282 | MultiByteToWideChar(CP_UTF8, 0, deviceID.c_str(), -1, wstr, wchars_num); |
| 283 | devID=wstr; |
| 284 | } |
| 285 |
| 286 | HRESULT res1, res2; |
| 287 | IAudioClient2* audioClient2=WindowsSandboxUtils::ActivateAudioDevice(devID.c_str(), &res1, &res2); |
| 288 | CHECK_RES(res1, "activate1"); |
| 289 | CHECK_RES(res2, "activate2"); |
| 290 |
| 291 | AudioClientProperties properties={}; |
| 292 | properties.cbSize=sizeof AudioClientProperties; |
| 293 | properties.eCategory=AudioCategory_Communications; |
| 294 | res = audioClient2->SetClientProperties(&properties); |
| 295 | CHECK_RES(res, "audioClient2->SetClientProperties"); |
| 296 |
| 297 | audioClient=audioClient2; |
| 298 | #endif |
| 299 |
| 300 | // {2C693079-3F59-49FD-964F-61C005EAA5D3} |
| 301 | const GUID guid = { 0x2c693079, 0x3f59, 0x49fd, { 0x96, 0x4f, 0x61, 0xc0, 0x5, 0xea, 0xa5, 0xd3 } }; |
| 302 | // Use 1000ms buffer to avoid resampling glitches on Windows 8.1 and older. This should not increase latency. |
| 303 | res = audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, 1000*10000, 0, &format, &guid); |
| 304 | CHECK_RES(res, "audioClient->Initialize"); |
| 305 |
| 306 | uint32_t bufSize; |
| 307 | res = audioClient->GetBufferSize(&bufSize); |
| 308 | CHECK_RES(res, "audioClient->GetBufferSize"); |
| 309 |
| 310 | LOGV("buffer size: %u", bufSize); |
| 311 | estimatedDelay=0; |
| 312 | REFERENCE_TIME latency, devicePeriod; |
| 313 | if(SUCCEEDED(audioClient->GetStreamLatency(&latency))){ |
| 314 | if(SUCCEEDED(audioClient->GetDevicePeriod(&devicePeriod, NULL))){ |
| 315 | estimatedDelay=(int32_t)(latency/10000+devicePeriod/10000); |
| 316 | } |
| 317 | } |
| 318 |
| 319 | res = audioClient->SetEventHandle(audioSamplesReadyEvent); |
| 320 | CHECK_RES(res, "audioClient->SetEventHandle"); |
| 321 |
| 322 | res = audioClient->GetService(IID_PPV_ARGS(&captureClient)); |
| 323 | CHECK_RES(res, "audioClient->GetService"); |
| 324 |
| 325 | #ifdef TGVOIP_WINDOWS_DESKTOP |
| 326 | res=audioClient->GetService(IID_PPV_ARGS(&audioSessionControl)); |
| 327 | CHECK_RES(res, "audioClient->GetService(IAudioSessionControl)"); |
| 328 |
| 329 | res=audioSessionControl->RegisterAudioSessionNotification(this); |
| 330 | CHECK_RES(res, "audioSessionControl->RegisterAudioSessionNotification"); |
| 331 | #endif |
| 332 |
| 333 | if(isRecording) |
| 334 | audioClient->Start(); |
| 335 |
| 336 | LOGV("set current input device done"); |
| 337 | } |
| 338 |
| 339 | DWORD WINAPI AudioInputWASAPI::StartThread(void* arg) { |
| 340 | LOGV("WASAPI capture thread starting"); |
| 341 | ((AudioInputWASAPI*)arg)->RunThread(); |
| 342 | return 0; |
| 343 | } |
| 344 |
| 345 | void AudioInputWASAPI::RunThread() { |
| 346 | if(failed) |
| 347 | return; |
| 348 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); |
| 349 |
| 350 | HANDLE waitArray[]={shutdownEvent, streamSwitchEvent, audioSamplesReadyEvent}; |
| 351 | HRESULT res=CoInitializeEx(NULL, COINIT_MULTITHREADED); |
| 352 | CHECK_RES(res, "CoInitializeEx in capture thread"); |
| 353 |
| 354 | uint32_t bufferSize=0; |
| 355 | uint64_t framesWritten=0; |
| 356 |
| 357 | bool running=true; |
| 358 | //double prevCallback=VoIPController::GetCurrentTime(); |
| 359 |
| 360 | while(running){ |
| 361 | DWORD waitResult=WaitForMultipleObjectsEx(3, waitArray, false, INFINITE, false); |
| 362 | if(waitResult==WAIT_OBJECT_0){ // shutdownEvent |
| 363 | LOGV("capture thread shutting down"); |
| 364 | running=false; |
| 365 | }else if(waitResult==WAIT_OBJECT_0+1){ // streamSwitchEvent |
| 366 | LOGV("stream switch"); |
| 367 | ActuallySetCurrentDevice(streamChangeToDevice); |
| 368 | ResetEvent(streamSwitchEvent); |
| 369 | bufferSize=0; |
| 370 | LOGV("stream switch done"); |
| 371 | }else if(waitResult==WAIT_OBJECT_0+2){ // audioSamplesReadyEvent |
| 372 | if(!audioClient) |
| 373 | continue; |
| 374 | res=captureClient->GetNextPacketSize(&bufferSize); |
| 375 | CHECK_RES(res, "captureClient->GetNextPacketSize"); |
| 376 | BYTE* data; |
| 377 | uint32_t framesAvailable=0; |
| 378 | DWORD flags; |
| 379 |
| 380 | res=captureClient->GetBuffer(&data, &framesAvailable, &flags, NULL, NULL); |
| 381 | CHECK_RES(res, "captureClient->GetBuffer"); |
| 382 | size_t dataLen=framesAvailable*2; |
| 383 | assert(remainingDataLen+dataLen<sizeof(remainingData)); |
| 384 |
| 385 | if(flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY){ |
| 386 | LOGW("Audio capture data discontinuity"); |
| 387 | } |
| 388 |
| 389 | //double t=VoIPController::GetCurrentTime(); |
| 390 | //LOGV("audio capture: %u, time %f, flags %u", framesAvailable, t-prevCallback, flags); |
| 391 | //prevCallback=t; |
| 392 |
| 393 | memcpy(remainingData+remainingDataLen, data, dataLen); |
| 394 | remainingDataLen+=dataLen; |
| 395 | while(remainingDataLen>960*2){ |
| 396 | if(isRecording) |
| 397 | InvokeCallback(remainingData, 960*2); |
| 398 |
| 399 | //LOGV("remaining data len %u", remainingDataLen); |
| 400 | memmove(remainingData, remainingData+(960*2), remainingDataLen-960*2); |
| 401 | remainingDataLen-=960*2; |
| 402 | } |
| 403 |
| 404 | res=captureClient->ReleaseBuffer(framesAvailable); |
| 405 | CHECK_RES(res, "captureClient->ReleaseBuffer"); |
| 406 | //estimatedDelay=(int32_t)((devicePosition-framesWritten)/48); |
| 407 |
| 408 | framesWritten+=framesAvailable; |
| 409 | } |
| 410 | } |
| 411 | } |
| 412 |
| 413 | #ifdef TGVOIP_WINDOWS_DESKTOP |
| 414 | HRESULT AudioInputWASAPI::OnSessionDisconnected(AudioSessionDisconnectReason reason) { |
| 415 | if(!isDefaultDevice){ |
| 416 | streamChangeToDevice="default"; |
| 417 | SetEvent(streamSwitchEvent); |
| 418 | } |
| 419 | return S_OK; |
| 420 | } |
| 421 |
| 422 | HRESULT AudioInputWASAPI::OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR newDevID) { |
| 423 | if(flow==eCapture && role==eCommunications && isDefaultDevice){ |
| 424 | streamChangeToDevice="default"; |
| 425 | SetEvent(streamSwitchEvent); |
| 426 | } |
| 427 | return S_OK; |
| 428 | } |
| 429 |
| 430 | ULONG AudioInputWASAPI::AddRef(){ |
| 431 | return InterlockedIncrement(&refCount); |
| 432 | } |
| 433 |
| 434 | ULONG AudioInputWASAPI::Release(){ |
| 435 | return InterlockedDecrement(&refCount); |
| 436 | } |
| 437 |
| 438 | HRESULT AudioInputWASAPI::QueryInterface(REFIID iid, void** obj){ |
| 439 | if(!obj){ |
| 440 | return E_POINTER; |
| 441 | } |
| 442 | *obj=NULL; |
| 443 |
| 444 | if(iid==IID_IUnknown){ |
| 445 | *obj=static_cast<IUnknown*>(static_cast<IAudioSessionEvents*>(this)); |
| 446 | AddRef(); |
| 447 | }else if(iid==__uuidof(IMMNotificationClient)){ |
| 448 | *obj=static_cast<IMMNotificationClient*>(this); |
| 449 | AddRef(); |
| 450 | }else if(iid==__uuidof(IAudioSessionEvents)){ |
| 451 | *obj=static_cast<IAudioSessionEvents*>(this); |
| 452 | AddRef(); |
| 453 | }else{ |
| 454 | return E_NOINTERFACE; |
| 455 | } |
| 456 |
| 457 | return S_OK; |
| 458 | } |
| 459 | #endif |