audio_driver_wasapi.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. /*************************************************************************/
  2. /* audio_driver_wasapi.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifdef WASAPI_ENABLED
  31. #include "audio_driver_wasapi.h"
  32. #include "os/os.h"
  33. #include "project_settings.h"
  34. #include <functiondiscoverykeys.h>
  35. #ifndef PKEY_Device_FriendlyName
  36. #undef DEFINE_PROPERTYKEY
  37. /* clang-format off */
  38. #define DEFINE_PROPERTYKEY(id, a, b, c, d, e, f, g, h, i, j, k, l) \
  39. const PROPERTYKEY id = { { a, b, c, { d, e, f, g, h, i, j, k, } }, l };
  40. /* clang-format on */
  41. DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14);
  42. #endif
  43. const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
  44. const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
  45. const IID IID_IAudioClient = __uuidof(IAudioClient);
  46. const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient);
  47. static bool default_device_changed = false;
  48. class CMMNotificationClient : public IMMNotificationClient {
  49. LONG _cRef;
  50. IMMDeviceEnumerator *_pEnumerator;
  51. public:
  52. CMMNotificationClient() :
  53. _cRef(1),
  54. _pEnumerator(NULL) {}
  55. ~CMMNotificationClient() {
  56. if ((_pEnumerator) != NULL) {
  57. (_pEnumerator)->Release();
  58. (_pEnumerator) = NULL;
  59. }
  60. }
  61. ULONG STDMETHODCALLTYPE AddRef() {
  62. return InterlockedIncrement(&_cRef);
  63. }
  64. ULONG STDMETHODCALLTYPE Release() {
  65. ULONG ulRef = InterlockedDecrement(&_cRef);
  66. if (0 == ulRef) {
  67. delete this;
  68. }
  69. return ulRef;
  70. }
  71. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) {
  72. if (IID_IUnknown == riid) {
  73. AddRef();
  74. *ppvInterface = (IUnknown *)this;
  75. } else if (__uuidof(IMMNotificationClient) == riid) {
  76. AddRef();
  77. *ppvInterface = (IMMNotificationClient *)this;
  78. } else {
  79. *ppvInterface = NULL;
  80. return E_NOINTERFACE;
  81. }
  82. return S_OK;
  83. }
  84. HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR pwstrDeviceId) {
  85. return S_OK;
  86. };
  87. HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR pwstrDeviceId) {
  88. return S_OK;
  89. }
  90. HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR pwstrDeviceId, DWORD dwNewState) {
  91. return S_OK;
  92. }
  93. HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId) {
  94. if (flow == eRender && role == eConsole) {
  95. default_device_changed = true;
  96. }
  97. return S_OK;
  98. }
  99. HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR pwstrDeviceId, const PROPERTYKEY key) {
  100. return S_OK;
  101. }
  102. };
  103. static CMMNotificationClient notif_client;
  104. Error AudioDriverWASAPI::init_device(bool reinit) {
  105. WAVEFORMATEX *pwfex;
  106. IMMDeviceEnumerator *enumerator = NULL;
  107. IMMDevice *device = NULL;
  108. CoInitialize(NULL);
  109. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  110. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  111. if (device_name == "Default") {
  112. hr = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device);
  113. } else {
  114. IMMDeviceCollection *devices = NULL;
  115. hr = enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &devices);
  116. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  117. LPWSTR strId = NULL;
  118. bool found = false;
  119. UINT count = 0;
  120. hr = devices->GetCount(&count);
  121. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  122. for (ULONG i = 0; i < count && !found; i++) {
  123. IMMDevice *device = NULL;
  124. hr = devices->Item(i, &device);
  125. ERR_BREAK(hr != S_OK);
  126. IPropertyStore *props = NULL;
  127. hr = device->OpenPropertyStore(STGM_READ, &props);
  128. ERR_BREAK(hr != S_OK);
  129. PROPVARIANT propvar;
  130. PropVariantInit(&propvar);
  131. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  132. ERR_BREAK(hr != S_OK);
  133. if (device_name == String(propvar.pwszVal)) {
  134. hr = device->GetId(&strId);
  135. ERR_BREAK(hr != S_OK);
  136. found = true;
  137. }
  138. PropVariantClear(&propvar);
  139. props->Release();
  140. device->Release();
  141. }
  142. if (found) {
  143. hr = enumerator->GetDevice(strId, &device);
  144. }
  145. if (strId) {
  146. CoTaskMemFree(strId);
  147. }
  148. if (device == NULL) {
  149. hr = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device);
  150. }
  151. }
  152. if (reinit) {
  153. // In case we're trying to re-initialize the device prevent throwing this error on the console,
  154. // otherwise if there is currently no device available this will spam the console.
  155. if (hr != S_OK) {
  156. return ERR_CANT_OPEN;
  157. }
  158. } else {
  159. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  160. }
  161. hr = enumerator->RegisterEndpointNotificationCallback(&notif_client);
  162. if (hr != S_OK) {
  163. ERR_PRINT("WASAPI: RegisterEndpointNotificationCallback error");
  164. }
  165. hr = device->Activate(IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&audio_client);
  166. if (reinit) {
  167. if (hr != S_OK) {
  168. return ERR_CANT_OPEN;
  169. }
  170. } else {
  171. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  172. }
  173. hr = audio_client->GetMixFormat(&pwfex);
  174. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  175. // Since we're using WASAPI Shared Mode we can't control any of these, we just tag along
  176. wasapi_channels = pwfex->nChannels;
  177. format_tag = pwfex->wFormatTag;
  178. bits_per_sample = pwfex->wBitsPerSample;
  179. switch (wasapi_channels) {
  180. case 2: // Stereo
  181. case 4: // Surround 3.1
  182. case 6: // Surround 5.1
  183. case 8: // Surround 7.1
  184. channels = wasapi_channels;
  185. break;
  186. default:
  187. WARN_PRINTS("WASAPI: Unsupported number of channels: " + itos(wasapi_channels));
  188. channels = 2;
  189. break;
  190. }
  191. if (format_tag == WAVE_FORMAT_EXTENSIBLE) {
  192. WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)pwfex;
  193. if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) {
  194. format_tag = WAVE_FORMAT_PCM;
  195. } else if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {
  196. format_tag = WAVE_FORMAT_IEEE_FLOAT;
  197. } else {
  198. ERR_PRINT("WASAPI: Format not supported");
  199. ERR_FAIL_V(ERR_CANT_OPEN);
  200. }
  201. } else {
  202. if (format_tag != WAVE_FORMAT_PCM && format_tag != WAVE_FORMAT_IEEE_FLOAT) {
  203. ERR_PRINT("WASAPI: Format not supported");
  204. ERR_FAIL_V(ERR_CANT_OPEN);
  205. }
  206. }
  207. DWORD streamflags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  208. if (mix_rate != pwfex->nSamplesPerSec) {
  209. streamflags |= AUDCLNT_STREAMFLAGS_RATEADJUST;
  210. pwfex->nSamplesPerSec = mix_rate;
  211. pwfex->nAvgBytesPerSec = pwfex->nSamplesPerSec * pwfex->nChannels * (pwfex->wBitsPerSample / 8);
  212. }
  213. hr = audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, streamflags, 0, 0, pwfex, NULL);
  214. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  215. event = CreateEvent(NULL, FALSE, FALSE, NULL);
  216. ERR_FAIL_COND_V(event == NULL, ERR_CANT_OPEN);
  217. hr = audio_client->SetEventHandle(event);
  218. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  219. hr = audio_client->GetService(IID_IAudioRenderClient, (void **)&render_client);
  220. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  221. UINT32 max_frames;
  222. hr = audio_client->GetBufferSize(&max_frames);
  223. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  224. // Due to WASAPI Shared Mode we have no control of the buffer size
  225. buffer_frames = max_frames;
  226. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  227. buffer_size = buffer_frames * channels;
  228. samples_in.resize(buffer_size);
  229. if (OS::get_singleton()->is_stdout_verbose()) {
  230. print_line("WASAPI: detected " + itos(channels) + " channels");
  231. print_line("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  232. }
  233. return OK;
  234. }
  235. Error AudioDriverWASAPI::finish_device() {
  236. if (audio_client) {
  237. if (active) {
  238. audio_client->Stop();
  239. active = false;
  240. }
  241. audio_client->Release();
  242. audio_client = NULL;
  243. }
  244. if (render_client) {
  245. render_client->Release();
  246. render_client = NULL;
  247. }
  248. if (audio_client) {
  249. audio_client->Release();
  250. audio_client = NULL;
  251. }
  252. return OK;
  253. }
  254. Error AudioDriverWASAPI::init() {
  255. mix_rate = GLOBAL_DEF("audio/mix_rate", DEFAULT_MIX_RATE);
  256. Error err = init_device();
  257. if (err != OK) {
  258. ERR_PRINT("WASAPI: init_device error");
  259. }
  260. active = false;
  261. exit_thread = false;
  262. thread_exited = false;
  263. mutex = Mutex::create(true);
  264. thread = Thread::create(thread_func, this);
  265. return OK;
  266. }
  267. Error AudioDriverWASAPI::reopen() {
  268. Error err = finish_device();
  269. if (err != OK) {
  270. ERR_PRINT("WASAPI: finish_device error");
  271. } else {
  272. err = init_device();
  273. if (err != OK) {
  274. ERR_PRINT("WASAPI: init_device error");
  275. } else {
  276. start();
  277. }
  278. }
  279. return err;
  280. }
  281. int AudioDriverWASAPI::get_mix_rate() const {
  282. return mix_rate;
  283. }
  284. AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {
  285. return get_speaker_mode_by_total_channels(channels);
  286. }
  287. Array AudioDriverWASAPI::get_device_list() {
  288. Array list;
  289. IMMDeviceCollection *devices = NULL;
  290. IMMDeviceEnumerator *enumerator = NULL;
  291. list.push_back(String("Default"));
  292. CoInitialize(NULL);
  293. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  294. ERR_FAIL_COND_V(hr != S_OK, Array());
  295. hr = enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &devices);
  296. ERR_FAIL_COND_V(hr != S_OK, Array());
  297. UINT count = 0;
  298. hr = devices->GetCount(&count);
  299. ERR_FAIL_COND_V(hr != S_OK, Array());
  300. for (ULONG i = 0; i < count; i++) {
  301. IMMDevice *device = NULL;
  302. hr = devices->Item(i, &device);
  303. ERR_BREAK(hr != S_OK);
  304. IPropertyStore *props = NULL;
  305. hr = device->OpenPropertyStore(STGM_READ, &props);
  306. ERR_BREAK(hr != S_OK);
  307. PROPVARIANT propvar;
  308. PropVariantInit(&propvar);
  309. hr = props->GetValue(PKEY_Device_FriendlyName, &propvar);
  310. ERR_BREAK(hr != S_OK);
  311. list.push_back(String(propvar.pwszVal));
  312. PropVariantClear(&propvar);
  313. props->Release();
  314. device->Release();
  315. }
  316. devices->Release();
  317. enumerator->Release();
  318. return list;
  319. }
  320. String AudioDriverWASAPI::get_device() {
  321. return device_name;
  322. }
  323. void AudioDriverWASAPI::set_device(String device) {
  324. new_device = device;
  325. }
  326. void AudioDriverWASAPI::write_sample(AudioDriverWASAPI *ad, BYTE *buffer, int i, int32_t sample) {
  327. if (ad->format_tag == WAVE_FORMAT_PCM) {
  328. switch (ad->bits_per_sample) {
  329. case 8:
  330. ((int8_t *)buffer)[i] = sample >> 24;
  331. break;
  332. case 16:
  333. ((int16_t *)buffer)[i] = sample >> 16;
  334. break;
  335. case 24:
  336. ((int8_t *)buffer)[i * 3 + 2] = sample >> 24;
  337. ((int8_t *)buffer)[i * 3 + 1] = sample >> 16;
  338. ((int8_t *)buffer)[i * 3 + 0] = sample >> 8;
  339. break;
  340. case 32:
  341. ((int32_t *)buffer)[i] = sample;
  342. break;
  343. }
  344. } else if (ad->format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  345. ((float *)buffer)[i] = (sample >> 16) / 32768.f;
  346. } else {
  347. ERR_PRINT("WASAPI: Unknown format tag");
  348. ad->exit_thread = true;
  349. }
  350. }
  351. void AudioDriverWASAPI::thread_func(void *p_udata) {
  352. AudioDriverWASAPI *ad = (AudioDriverWASAPI *)p_udata;
  353. while (!ad->exit_thread) {
  354. if (ad->active) {
  355. ad->lock();
  356. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  357. ad->unlock();
  358. } else {
  359. for (unsigned int i = 0; i < ad->buffer_size; i++) {
  360. ad->samples_in[i] = 0;
  361. }
  362. }
  363. unsigned int left_frames = ad->buffer_frames;
  364. unsigned int buffer_idx = 0;
  365. while (left_frames > 0 && ad->audio_client) {
  366. WaitForSingleObject(ad->event, 1000);
  367. UINT32 cur_frames;
  368. HRESULT hr = ad->audio_client->GetCurrentPadding(&cur_frames);
  369. if (hr == S_OK) {
  370. // Check how much frames are available on the WASAPI buffer
  371. UINT32 avail_frames = ad->buffer_frames - cur_frames;
  372. UINT32 write_frames = avail_frames > left_frames ? left_frames : avail_frames;
  373. BYTE *buffer = NULL;
  374. hr = ad->render_client->GetBuffer(write_frames, &buffer);
  375. if (hr == S_OK) {
  376. // We're using WASAPI Shared Mode so we must convert the buffer
  377. if (ad->channels == ad->wasapi_channels) {
  378. for (unsigned int i = 0; i < write_frames * ad->channels; i++) {
  379. ad->write_sample(ad, buffer, i, ad->samples_in[buffer_idx++]);
  380. }
  381. } else {
  382. for (unsigned int i = 0; i < write_frames; i++) {
  383. for (unsigned int j = 0; j < MIN(ad->channels, ad->wasapi_channels); j++) {
  384. ad->write_sample(ad, buffer, i * ad->wasapi_channels + j, ad->samples_in[buffer_idx++]);
  385. }
  386. if (ad->wasapi_channels > ad->channels) {
  387. for (unsigned int j = ad->channels; j < ad->wasapi_channels; j++) {
  388. ad->write_sample(ad, buffer, i * ad->wasapi_channels + j, 0);
  389. }
  390. }
  391. }
  392. }
  393. hr = ad->render_client->ReleaseBuffer(write_frames, 0);
  394. if (hr != S_OK) {
  395. ERR_PRINT("WASAPI: Release buffer error");
  396. }
  397. left_frames -= write_frames;
  398. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  399. // Device is not valid anymore, reopen it
  400. Error err = ad->finish_device();
  401. if (err != OK) {
  402. ERR_PRINT("WASAPI: finish_device error");
  403. } else {
  404. // We reopened the device and samples_in may have resized, so invalidate the current left_frames
  405. left_frames = 0;
  406. }
  407. } else {
  408. ERR_PRINT("WASAPI: Get buffer error");
  409. ad->exit_thread = true;
  410. }
  411. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  412. // Device is not valid anymore, reopen it
  413. Error err = ad->finish_device();
  414. if (err != OK) {
  415. ERR_PRINT("WASAPI: finish_device error");
  416. } else {
  417. // We reopened the device and samples_in may have resized, so invalidate the current left_frames
  418. left_frames = 0;
  419. }
  420. } else {
  421. ERR_PRINT("WASAPI: GetCurrentPadding error");
  422. }
  423. }
  424. // If we're using the Default device and it changed finish it so we'll re-init the device
  425. if (ad->device_name == "Default" && default_device_changed) {
  426. Error err = ad->finish_device();
  427. if (err != OK) {
  428. ERR_PRINT("WASAPI: finish_device error");
  429. }
  430. default_device_changed = false;
  431. }
  432. // User selected a new device, finish the current one so we'll init the new device
  433. if (ad->device_name != ad->new_device) {
  434. ad->device_name = ad->new_device;
  435. Error err = ad->finish_device();
  436. if (err != OK) {
  437. ERR_PRINT("WASAPI: finish_device error");
  438. }
  439. }
  440. if (!ad->audio_client) {
  441. Error err = ad->init_device(true);
  442. if (err == OK) {
  443. ad->start();
  444. }
  445. }
  446. }
  447. ad->thread_exited = true;
  448. }
  449. void AudioDriverWASAPI::start() {
  450. if (audio_client) {
  451. HRESULT hr = audio_client->Start();
  452. if (hr != S_OK) {
  453. ERR_PRINT("WASAPI: Start failed");
  454. } else {
  455. active = true;
  456. }
  457. }
  458. }
  459. void AudioDriverWASAPI::lock() {
  460. if (mutex)
  461. mutex->lock();
  462. }
  463. void AudioDriverWASAPI::unlock() {
  464. if (mutex)
  465. mutex->unlock();
  466. }
  467. void AudioDriverWASAPI::finish() {
  468. if (thread) {
  469. exit_thread = true;
  470. Thread::wait_to_finish(thread);
  471. memdelete(thread);
  472. thread = NULL;
  473. }
  474. finish_device();
  475. if (mutex) {
  476. memdelete(mutex);
  477. mutex = NULL;
  478. }
  479. }
  480. AudioDriverWASAPI::AudioDriverWASAPI() {
  481. audio_client = NULL;
  482. render_client = NULL;
  483. mutex = NULL;
  484. thread = NULL;
  485. format_tag = 0;
  486. bits_per_sample = 0;
  487. samples_in.clear();
  488. buffer_size = 0;
  489. channels = 0;
  490. wasapi_channels = 0;
  491. mix_rate = 0;
  492. buffer_frames = 0;
  493. thread_exited = false;
  494. exit_thread = false;
  495. active = false;
  496. device_name = "Default";
  497. new_device = "Default";
  498. }
  499. #endif