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