mswasapi.cpp 21.3 KB
Newer Older
1
/*
2
mswasapi.cpp
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

mediastreamer2 library - modular sound and video processing and streaming
Windows Audio Session API sound card plugin for mediastreamer2
Copyright (C) 2010-2013 Belledonne Communications, Grenoble, France

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
20
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 22 23 24
*/


#include "mediastreamer2/msfilter.h"
25 26
#include "mediastreamer2/mssndcard.h"

27
#include "mswasapi.h"
28
#include "mswasapi_reader.h"
29
#include "mswasapi_writer.h"
30

31 32
#include <string>
#include <locale>
33

34 35
const IID IID_IAudioCaptureClient = __uuidof(IAudioCaptureClient);
const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient);
36
const IID IID_ISimpleAudioVolume = __uuidof(ISimpleAudioVolume);
37
#if defined(MS2_WINDOWS_PHONE) || defined(MS2_WINDOWS_UNIVERSAL)
38 39 40
const IID IID_IAudioClient2 = __uuidof(IAudioClient2);
#else
const IID IID_IAudioClient = __uuidof(IAudioClient);
41 42
const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
43
#endif
44 45 46 47 48 49

/******************************************************************************
 * Methods to (de)initialize and run the WASAPI sound capture filter          *
 *****************************************************************************/

static void ms_wasapi_read_init(MSFilter *f) {
50
	MSWASAPIReaderPtr r = MSWASAPIReaderNew(f);
51
	f->data = r;
52 53 54
}

static void ms_wasapi_read_preprocess(MSFilter *f) {
55
	MSWASAPIReaderType r = MSWASAPI_READER(f->data);
56
	r->start();
57 58 59
}

static void ms_wasapi_read_process(MSFilter *f) {
60
	MSWASAPIReaderType r = MSWASAPI_READER(f->data);
61
	r->feed(f);
62 63 64
}

static void ms_wasapi_read_postprocess(MSFilter *f) {
65
	MSWASAPIReaderType r = MSWASAPI_READER(f->data);
66
	r->stop();
67
	
68 69 70
}

static void ms_wasapi_read_uninit(MSFilter *f) {
71 72
	MSWASAPIReaderType r = MSWASAPI_READER(f->data);
	r->deactivate();
73
	MSWASAPIReaderDelete(static_cast<MSWASAPIReaderPtr>(f->data));
74 75 76 77 78 79 80 81
}


/******************************************************************************
 * Methods to configure the WASAPI sound capture filter                       *
 *****************************************************************************/

static int ms_wasapi_read_set_sample_rate(MSFilter *f, void *arg) {
82 83 84
	/* This is not supported: the Audio Client requires to use the native sample rate. */
	MS_UNUSED(f), MS_UNUSED(arg);
	return -1;
85 86 87
}

static int ms_wasapi_read_get_sample_rate(MSFilter *f, void *arg) {
88
	MSWASAPIReaderType r = MSWASAPI_READER(f->data);
89 90 91 92 93 94 95 96 97 98 99
	*((int *)arg) = r->getRate();
	return 0;
}

static int ms_wasapi_read_set_nchannels(MSFilter *f, void *arg) {
	/* This is not supported: the Audio Client requires to use 1 channel. */
	MS_UNUSED(f), MS_UNUSED(arg);
	return -1;
}

static int ms_wasapi_read_get_nchannels(MSFilter *f, void *arg) {
100
	MSWASAPIReaderType r = MSWASAPI_READER(f->data);
101
	*((int *)arg) = r->getNChannels();
102 103 104
	return 0;
}

105 106 107 108 109 110 111 112 113 114 115 116 117
static int ms_wasapi_read_set_volume_gain(MSFilter *f, void *arg) {
	MSWASAPIReaderType r = MSWASAPI_READER(f->data);
	r->setVolumeLevel(*(float *)arg);
	return 0;
}

static int ms_wasapi_read_get_volume_gain(MSFilter *f, void *arg) {
	MSWASAPIReaderType r = MSWASAPI_READER(f->data);
	float *volume = (float *)arg;
	*volume = r->getVolumeLevel();
	return *volume >= 0.0f ? 0 : -1;
}

118 119 120
static MSFilterMethod ms_wasapi_read_methods[] = {
	{	MS_FILTER_SET_SAMPLE_RATE,	ms_wasapi_read_set_sample_rate	},
	{	MS_FILTER_GET_SAMPLE_RATE,	ms_wasapi_read_get_sample_rate	},
121 122
	{	MS_FILTER_SET_NCHANNELS,	ms_wasapi_read_set_nchannels	},
	{	MS_FILTER_GET_NCHANNELS,	ms_wasapi_read_get_nchannels	},
123 124
	{	MS_AUDIO_CAPTURE_SET_VOLUME_GAIN, ms_wasapi_read_set_volume_gain	},
	{	MS_AUDIO_CAPTURE_GET_VOLUME_GAIN, ms_wasapi_read_get_volume_gain	},
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
	{	0,				NULL				}
};


/******************************************************************************
 * Definition of the WASAPI sound capture filter                              *
 *****************************************************************************/

#define MS_WASAPI_READ_ID			MS_FILTER_PLUGIN_ID
#define MS_WASAPI_READ_NAME			"MSWASAPIRead"
#define MS_WASAPI_READ_DESCRIPTION	"Windows Audio Session sound capture"
#define MS_WASAPI_READ_CATEGORY		MS_FILTER_OTHER
#define MS_WASAPI_READ_ENC_FMT		NULL
#define MS_WASAPI_READ_NINPUTS		0
#define MS_WASAPI_READ_NOUTPUTS		1
#define MS_WASAPI_READ_FLAGS		0

#ifndef _MSC_VER

MSFilterDesc ms_wasapi_read_desc = {
	.id = MS_WASAPI_READ_ID,
	.name = MS_WASAPI_READ_NAME,
	.text = MS_WASAPI_READ_DESCRIPTION,
	.category = MS_WASAPI_READ_CATEGORY,
	.enc_fmt = MS_WASAPI_READ_ENC_FMT,
	.ninputs = MS_WASAPI_READ_NINPUTS,
	.noutputs = MS_WASAPI_READ_NOUTPUTS,
	.init = ms_wasapi_read_init,
	.preprocess = ms_wasapi_read_preprocess,
	.process = ms_wasapi_read_process,
	.postprocess = ms_wasapi_read_postprocess,
	.uninit = ms_wasapi_read_uninit,
	.methods = ms_wasapi_read_methods,
	.flags = MS_WASAPI_READ_FLAGS
};

#else

MSFilterDesc ms_wasapi_read_desc = {
	MS_WASAPI_READ_ID,
	MS_WASAPI_READ_NAME,
	MS_WASAPI_READ_DESCRIPTION,
	MS_WASAPI_READ_CATEGORY,
	MS_WASAPI_READ_ENC_FMT,
	MS_WASAPI_READ_NINPUTS,
	MS_WASAPI_READ_NOUTPUTS,
	ms_wasapi_read_init,
	ms_wasapi_read_preprocess,
	ms_wasapi_read_process,
	ms_wasapi_read_postprocess,
	ms_wasapi_read_uninit,
	ms_wasapi_read_methods,
	MS_WASAPI_READ_FLAGS
};

#endif

MS_FILTER_DESC_EXPORT(ms_wasapi_read_desc)



186

187 188 189 190 191
/******************************************************************************
 * Methods to (de)initialize and run the WASAPI sound output filter           *
 *****************************************************************************/

static void ms_wasapi_write_init(MSFilter *f) {
192
	MSWASAPIWriterPtr w = MSWASAPIWriterNew();
193
	f->data = w;
194 195 196
}

static void ms_wasapi_write_preprocess(MSFilter *f) {
197
	MSWASAPIWriterType w = MSWASAPI_WRITER(f->data);
198
	w->start();
199 200 201
}

static void ms_wasapi_write_process(MSFilter *f) {
202
	MSWASAPIWriterType w = MSWASAPI_WRITER(f->data);
203
	w->feed(f);
204 205 206
}

static void ms_wasapi_write_postprocess(MSFilter *f) {
207
	MSWASAPIWriterType w = MSWASAPI_WRITER(f->data);
208
	w->stop();
209 210 211
}

static void ms_wasapi_write_uninit(MSFilter *f) {
212 213
	MSWASAPIWriterType w = MSWASAPI_WRITER(f->data);
	w->deactivate();
214
	MSWASAPIWriterDelete(static_cast<MSWASAPIWriterPtr>(f->data));
215 216 217 218 219 220 221 222
}


/******************************************************************************
 * Methods to configure the WASAPI sound output filter                        *
 *****************************************************************************/

static int ms_wasapi_write_set_sample_rate(MSFilter *f, void *arg) {
223 224 225
	/* This is not supported: the Audio Client requires to use the native sample rate. */
	MS_UNUSED(f), MS_UNUSED(arg);
	return -1;
226 227 228
}

static int ms_wasapi_write_get_sample_rate(MSFilter *f, void *arg) {
229
	MSWASAPIWriterType w = MSWASAPI_WRITER(f->data);
230 231 232 233 234 235 236 237 238 239 240
	*((int *)arg) = w->getRate();
	return 0;
}

static int ms_wasapi_write_set_nchannels(MSFilter *f, void *arg) {
	/* This is not supported: the Audio Client requires to use 2 channels. */
	MS_UNUSED(f), MS_UNUSED(arg);
	return -1;
}

static int ms_wasapi_write_get_nchannels(MSFilter *f, void *arg) {
241
	MSWASAPIWriterType w = MSWASAPI_WRITER(f->data);
242
	*((int *)arg) = w->getNChannels();
243 244 245
	return 0;
}

246 247 248 249 250 251 252 253 254 255 256 257 258
static int ms_wasapi_write_set_volume_gain(MSFilter *f, void *arg) {
	MSWASAPIWriterType w = MSWASAPI_WRITER(f->data);
	w->setVolumeLevel(*(float *)arg);
	return 0;
}

static int ms_wasapi_write_get_volume_gain(MSFilter *f, void *arg) {
	MSWASAPIWriterType w = MSWASAPI_WRITER(f->data);
	float *volume = (float *)arg;
	*volume = w->getVolumeLevel();
	return *volume >= 0.0f ? 0 : -1;
}

259 260 261
static MSFilterMethod ms_wasapi_write_methods[] = {
	{	MS_FILTER_SET_SAMPLE_RATE,	ms_wasapi_write_set_sample_rate	},
	{	MS_FILTER_GET_SAMPLE_RATE,	ms_wasapi_write_get_sample_rate	},
262 263
	{	MS_FILTER_SET_NCHANNELS,	ms_wasapi_write_set_nchannels	},
	{	MS_FILTER_GET_NCHANNELS,	ms_wasapi_write_get_nchannels	},
264 265
	{	MS_AUDIO_PLAYBACK_SET_VOLUME_GAIN, ms_wasapi_write_set_volume_gain	},
	{	MS_AUDIO_PLAYBACK_GET_VOLUME_GAIN, ms_wasapi_write_get_volume_gain	},
266
	{	0,							NULL							}
267 268 269 270 271 272 273 274 275 276 277 278 279 280
};


/******************************************************************************
 * Definition of the WASAPI sound output filter                               *
 *****************************************************************************/

#define MS_WASAPI_WRITE_ID				MS_FILTER_PLUGIN_ID
#define MS_WASAPI_WRITE_NAME			"MSWASAPIWrite"
#define MS_WASAPI_WRITE_DESCRIPTION		"Windows Audio Session sound output"
#define MS_WASAPI_WRITE_CATEGORY		MS_FILTER_OTHER
#define MS_WASAPI_WRITE_ENC_FMT			NULL
#define MS_WASAPI_WRITE_NINPUTS			1
#define MS_WASAPI_WRITE_NOUTPUTS		0
281
#define MS_WASAPI_WRITE_FLAGS			MS_FILTER_IS_PUMP
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325

#ifndef _MSC_VER

MSFilterDesc ms_wasapi_write_desc = {
	.id = MS_WASAPI_WRITE_ID,
	.name = MS_WASAPI_WRITE_NAME,
	.text = MS_WASAPI_WRITE_DESCRIPTION,
	.category = MS_WASAPI_WRITE_CATEGORY,
	.enc_fmt = MS_WASAPI_WRITE_ENC_FMT,
	.ninputs = MS_WASAPI_WRITE_NINPUTS,
	.noutputs = MS_WASAPI_WRITE_NOUTPUTS,
	.init = ms_wasapi_write_init,
	.preprocess = ms_wasapi_write_preprocess,
	.process = ms_wasapi_write_process,
	.postprocess = ms_wasapi_write_postprocess,
	.uninit = ms_wasapi_write_uninit,
	.methods = ms_wasapi_write_methods,
	.flags = MS_WASAPI_WRITE_FLAGS
};

#else

MSFilterDesc ms_wasapi_write_desc = {
	MS_WASAPI_WRITE_ID,
	MS_WASAPI_WRITE_NAME,
	MS_WASAPI_WRITE_DESCRIPTION,
	MS_WASAPI_WRITE_CATEGORY,
	MS_WASAPI_WRITE_ENC_FMT,
	MS_WASAPI_WRITE_NINPUTS,
	MS_WASAPI_WRITE_NOUTPUTS,
	ms_wasapi_write_init,
	ms_wasapi_write_preprocess,
	ms_wasapi_write_process,
	ms_wasapi_write_postprocess,
	ms_wasapi_write_uninit,
	ms_wasapi_write_methods,
	MS_WASAPI_WRITE_FLAGS
};

#endif

MS_FILTER_DESC_EXPORT(ms_wasapi_write_desc)


326

327 328 329 330
static void ms_wasapi_snd_card_detect(MSSndCardManager *m);
static MSFilter *ms_wasapi_snd_card_create_reader(MSSndCard *card);
static MSFilter *ms_wasapi_snd_card_create_writer(MSSndCard *card);

331 332 333 334 335 336 337 338 339 340 341
static void ms_wasapi_snd_card_init(MSSndCard *card) {
	WasapiSndCard *c = static_cast<WasapiSndCard *>(ms_new0(WasapiSndCard, 1));
	card->data = c;
}

static void ms_wasapi_snd_card_uninit(MSSndCard *card) {
	WasapiSndCard *c = static_cast<WasapiSndCard *>(card->data);
	if (c->id_vector) delete c->id_vector;
	ms_free(c);
}

342
static MSSndCardDesc ms_wasapi_snd_card_desc = {
343
	"WASAPI",
344
	ms_wasapi_snd_card_detect,
345
	ms_wasapi_snd_card_init,
346 347 348 349 350 351 352
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	ms_wasapi_snd_card_create_reader,
	ms_wasapi_snd_card_create_writer,
353
	ms_wasapi_snd_card_uninit,
354 355 356
	NULL,
	NULL
};
357

358
#if defined(MS2_WINDOWS_PHONE)
359
static MSSndCard *ms_wasapi_phone_snd_card_new(void) {
360 361 362 363
	MSSndCard *card = ms_snd_card_new(&ms_wasapi_snd_card_desc);
	card->name = ms_strdup("WASAPI sound card");
	card->latency = 250;
	return card;
364
}
365

366 367 368 369 370 371 372 373 374 375 376 377 378
#elif defined(MS2_WINDOWS_UNIVERSAL)

class MSWASAPIDeviceEnumerator
{
public:
	MSWASAPIDeviceEnumerator() : _l(NULL) {
		_DetectEvent = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
		if (!_DetectEvent) {
			ms_error("mswasapi: Could not create detect event [%i]", GetLastError());
			return;
		}
	}
	~MSWASAPIDeviceEnumerator() {
379
		bctbx_list_free(_l);
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
		if (_DetectEvent != INVALID_HANDLE_VALUE) {
			CloseHandle(_DetectEvent);
			_DetectEvent = INVALID_HANDLE_VALUE;
		}
	}

	MSSndCard *NewCard(String^ DeviceId, const char *name, uint8_t capabilities) {
		const wchar_t *id = DeviceId->Data();
		MSSndCard *card = ms_snd_card_new(&ms_wasapi_snd_card_desc);
		WasapiSndCard *wasapicard = static_cast<WasapiSndCard *>(card->data);
		card->name = ms_strdup(name);
		card->capabilities = capabilities;
		wasapicard->id_vector = new std::vector<wchar_t>(wcslen(id) + 1);
		wcscpy_s(&wasapicard->id_vector->front(), wasapicard->id_vector->size(), id);
		wasapicard->id = &wasapicard->id_vector->front();
		return card;
	}

	void AddOrUpdateCard(String^ DeviceId, String^ DeviceName, DeviceClass dc) {
		char *name;
400
		const bctbx_list_t *elem = _l;
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
		size_t inputlen;
		size_t returnlen;
		uint8_t capabilities = 0;

		inputlen = wcslen(DeviceName->Data()) + 1;
		name = (char *)ms_malloc(inputlen);
		if (wcstombs_s(&returnlen, name, inputlen, DeviceName->Data(), inputlen) != 0) {
			ms_error("mswasapi: Cannot convert card name to multi-byte string.");
			return;
		}
		switch (dc) {
		case DeviceClass::AudioRender:
			capabilities = MS_SND_CARD_CAP_PLAYBACK;
			break;
		case DeviceClass::AudioCapture:
			capabilities = MS_SND_CARD_CAP_CAPTURE;
			break;
		}

		for (; elem != NULL; elem = elem->next) {
			MSSndCard *card = static_cast<MSSndCard *>(elem->data);
			WasapiSndCard *d = static_cast<WasapiSndCard *>(card->data);
			if (wcscmp(d->id, DeviceId->Data()) == 0) {
				/* Update an existing card. */
				if (card->name != NULL) {
					ms_free(card->name);
					card->name = ms_strdup(name);
				}
				card->capabilities |= capabilities;
				ms_free(name);
				return;
			}
		}

		/* Add a new card. */
436
		_l = bctbx_list_append(_l, NewCard(DeviceId, name, capabilities));
437 438 439 440 441 442 443 444 445 446 447 448 449
		ms_free(name);
	}

	void Detect(DeviceClass dc) {
		_dc = dc;
		String ^DefaultId;
		String ^DefaultName = "Default audio card";
		if (_dc == DeviceClass::AudioCapture) {
			DefaultId = MediaDevice::GetDefaultAudioCaptureId(AudioDeviceRole::Communications);
		} else {
			DefaultId = MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Communications);
		}
		AddOrUpdateCard(DefaultId, DefaultName, _dc);
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
		Windows::Foundation::IAsyncOperation<DeviceInformationCollection^>^ op = DeviceInformation::FindAllAsync(_dc);
		op->Completed = ref new Windows::Foundation::AsyncOperationCompletedHandler<DeviceInformationCollection^>(
				[this](Windows::Foundation::IAsyncOperation<DeviceInformationCollection^>^ asyncOp, Windows::Foundation::AsyncStatus asyncStatus) {
			if (asyncStatus == Windows::Foundation::AsyncStatus::Completed) {
				DeviceInformationCollection^ deviceInfoCollection = asyncOp->GetResults();
				if ((deviceInfoCollection == nullptr) || (deviceInfoCollection->Size == 0)) {
					ms_error("mswasapi: No audio device found");
				}
				else {
					try {
						for (unsigned int i = 0; i < deviceInfoCollection->Size; i++) {
							DeviceInformation^ deviceInfo = deviceInfoCollection->GetAt(i);
							AddOrUpdateCard(deviceInfo->Id, deviceInfo->Name, _dc);
						}
					}
					catch (Platform::Exception^ e) {
						ms_error("mswaspi: Error of audio device detection");
467 468
					}
				}
469 470
			} else {
				ms_error("mswasapi: DeviceInformation::FindAllAsync failed");
471 472 473 474 475 476 477 478 479 480 481
			}
			SetEvent(_DetectEvent);
		});
		WaitForSingleObjectEx(_DetectEvent, INFINITE, FALSE);
	}

	void Detect() {
		Detect(DeviceClass::AudioCapture);
		Detect(DeviceClass::AudioRender);
	}

482
	bctbx_list_t *GetList() { return _l; }
483 484

private:
485
	bctbx_list_t *_l;
486 487 488 489
	DeviceClass _dc;
	HANDLE _DetectEvent;
};

490 491
#else

492 493 494 495 496
static MSSndCard *ms_wasapi_snd_card_new(LPWSTR id, const char *name, uint8_t capabilities) {
	MSSndCard *card = ms_snd_card_new(&ms_wasapi_snd_card_desc);
	WasapiSndCard *wasapicard = static_cast<WasapiSndCard *>(card->data);
	card->name = ms_strdup(name);
	card->capabilities = capabilities;
497
	card->latency = (capabilities & MS_SND_CARD_CAP_CAPTURE) ? 70 : 0;
498
	wasapicard->id_vector = new std::vector<wchar_t>(wcslen(id) + 1);
499 500
	wcscpy_s(&wasapicard->id_vector->front(), wasapicard->id_vector->size(), id);
	wasapicard->id = &wasapicard->id_vector->front();
501 502 503
	return card;
}

504
static void add_or_update_card(MSSndCardManager *m, bctbx_list_t **l, LPWSTR id, LPWSTR wname, EDataFlow data_flow) {
505
	MSSndCard *card;
506
	const bctbx_list_t *elem = *l;
507
	uint8_t capabilities = 0;
508 509
	char *idStr = NULL;
	char *nameStr = NULL;
510
	size_t inputlen = wcslen(wname) + 1;
511
	size_t returnlen;
512 513 514 515 516 517 518 519
	UINT currentCodePage = GetACP();
	int sizeNeeded = WideCharToMultiByte(currentCodePage, 0, wname, inputlen, NULL, 0, NULL, NULL);
	std::string strConversion( sizeNeeded, 0 );
	if(WideCharToMultiByte(currentCodePage, 0, wname, inputlen, &strConversion[0], sizeNeeded, NULL, NULL)){
		nameStr = (char *)ms_malloc(strConversion.length()+1 );
		strcpy(nameStr, strConversion.c_str());
	}
	if(!nameStr){
520
		ms_error("mswasapi: Cannot convert card name to multi-byte string.");
521
		goto error;
522
	}
523 524 525 526 527 528 529
	inputlen = wcslen(id) + 1;
	idStr = (char *)ms_malloc(inputlen);
	if (!idStr || wcstombs_s(&returnlen, idStr, inputlen, id, inputlen) != 0) {
		ms_error("mswasapi: Cannot convert card id to multi-byte string.");
		goto error;
	}
	char *name = bctbx_strdup_printf("%s--%s", nameStr, idStr);	
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
	switch (data_flow) {
	case eRender:
		capabilities = MS_SND_CARD_CAP_PLAYBACK;
		break;
	case eCapture:
		capabilities = MS_SND_CARD_CAP_CAPTURE;
		break;
	case eAll:
	default:
		capabilities = MS_SND_CARD_CAP_PLAYBACK | MS_SND_CARD_CAP_CAPTURE;
		break;
	}

	for (; elem != NULL; elem = elem->next){
		card = static_cast<MSSndCard *>(elem->data);
		if (strcmp(card->name, name) == 0){
			/* Update an existing card. */
			WasapiSndCard *d = static_cast<WasapiSndCard *>(card->data);
			card->capabilities |= capabilities;
549 550 551 552 553 554
			if (nameStr) {
				ms_free(nameStr);
			}
			if (idStr) {
				ms_free(idStr);
			}
555 556 557 558 559
			return;
		}
	}

	/* Add a new card. */
560
	*l = bctbx_list_append(*l, ms_wasapi_snd_card_new(id, name, capabilities));
561 562 563 564 565 566 567
	error:
	if (nameStr) {
		ms_free(nameStr);
	}
	if (idStr) {
		ms_free(idStr);
	}
568 569
}

570
static void add_endpoint(MSSndCardManager *m, EDataFlow data_flow, bctbx_list_t **l, IMMDevice *pEndpoint) {
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
	IPropertyStore *pProps = NULL;
	LPWSTR pwszID = NULL;
	HRESULT result = pEndpoint->GetId(&pwszID);
	REPORT_ERROR("mswasapi: Could not get ID of audio endpoint", result);
	result = pEndpoint->OpenPropertyStore(STGM_READ, &pProps);
	REPORT_ERROR("mswasapi: Could not open property store", result);
	PROPVARIANT varName;
	PropVariantInit(&varName);
	result = pProps->GetValue(PKEY_Device_FriendlyName, &varName);
	REPORT_ERROR("mswasapi: Could not get friendly-name of audio endpoint", result);
	add_or_update_card(m, l, pwszID, varName.pwszVal, data_flow);
	CoTaskMemFree(pwszID);
	pwszID = NULL;
	PropVariantClear(&varName);
	SAFE_RELEASE(pProps);
error:
	CoTaskMemFree(pwszID);
	SAFE_RELEASE(pProps);
}

591
static void ms_wasapi_snd_card_detect_with_data_flow(MSSndCardManager *m, EDataFlow data_flow, bctbx_list_t **l) {
592 593 594
	IMMDeviceEnumerator *pEnumerator = NULL;
	IMMDeviceCollection *pCollection = NULL;
	IMMDevice *pEndpoint = NULL;
595 596 597
#ifdef ENABLE_MICROSOFT_STORE_APP
	HRESULT result = CoInitializeEx(NULL, COINIT_MULTITHREADED);
#else
598
	HRESULT result = CoInitialize(NULL);
599
#endif
600 601 602

	result = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&pEnumerator);

603
	REPORT_ERROR("mswasapi: Could not create an instance of the device enumerator", result);
604 605 606 607 608
	result = pEnumerator->GetDefaultAudioEndpoint(data_flow, eCommunications, &pEndpoint);
	if (result == S_OK) {
		add_endpoint(m, data_flow, l, pEndpoint);
		SAFE_RELEASE(pEndpoint);
	}
609 610 611 612 613 614 615 616 617 618 619 620
	result = pEnumerator->EnumAudioEndpoints(data_flow, DEVICE_STATE_ACTIVE, &pCollection);
	REPORT_ERROR("mswasapi: Could not enumerate audio endpoints", result);
	UINT count;
	result = pCollection->GetCount(&count);
	REPORT_ERROR("mswasapi: Could not get the number of audio endpoints", result);
	if (count == 0) {
		ms_warning("mswasapi: No audio endpoint found");
		return;
	}
	for (ULONG i = 0; i < count; i++) {
		result = pCollection->Item(i, &pEndpoint);
		REPORT_ERROR("mswasapi: Could not get pointer to audio endpoint", result);
621
		add_endpoint(m, data_flow, l, pEndpoint);
622 623 624 625 626 627 628 629
		SAFE_RELEASE(pEndpoint);
	}
error:
	SAFE_RELEASE(pEnumerator);
	SAFE_RELEASE(pCollection);
	SAFE_RELEASE(pEndpoint);
}
#endif
630

631
static void ms_wasapi_snd_card_detect(MSSndCardManager *m) {
632
#if defined(MS2_WINDOWS_PHONE)
633
	MSSndCard *card = ms_wasapi_phone_snd_card_new();
634
	ms_snd_card_set_manager(m, card);
635
	ms_snd_card_manager_add_card(m, card);
636 637 638 639 640
#elif defined(MS2_WINDOWS_UNIVERSAL)
	MSWASAPIDeviceEnumerator *enumerator = new MSWASAPIDeviceEnumerator();
	enumerator->Detect();
	ms_snd_card_manager_prepend_cards(m, enumerator->GetList());
	delete enumerator;
641
#else
642
	bctbx_list_t *l = NULL;
643 644 645
	ms_wasapi_snd_card_detect_with_data_flow(m, eCapture, &l);
	ms_wasapi_snd_card_detect_with_data_flow(m, eRender, &l);
	ms_snd_card_manager_prepend_cards(m, l);
646
	bctbx_list_free(l);
647
#endif
648 649 650
}

static MSFilter *ms_wasapi_snd_card_create_reader(MSSndCard *card) {
651
	MSFilter *f = ms_factory_create_filter_from_desc(ms_snd_card_get_factory(card), &ms_wasapi_read_desc);
652
	WasapiSndCard *wasapicard = static_cast<WasapiSndCard *>(card->data);
653
	MSWASAPIReaderType reader = MSWASAPI_READER(f->data);
654 655
	reader->init(wasapicard->id);
	return f;
656 657 658
}

static MSFilter *ms_wasapi_snd_card_create_writer(MSSndCard *card) {
659
	MSFilter *f = ms_factory_create_filter_from_desc(ms_snd_card_get_factory(card), &ms_wasapi_write_desc);
660
	WasapiSndCard *wasapicard = static_cast<WasapiSndCard *>(card->data);
661
	MSWASAPIWriterType writer = MSWASAPI_WRITER(f->data);
662
	writer->init(wasapicard->id, f);
663
	return f;
664 665 666 667 668
}




669
#ifdef _MSC_VER
670
#define MS_PLUGIN_DECLARE(type) extern "C" __declspec(dllexport) type
671
#else
672
#define MS_PLUGIN_DECLARE(type) extern "C" type
673 674
#endif

675
MS_PLUGIN_DECLARE(void) libmswasapi_init(MSFactory *factory) {
Ghislain MARY's avatar
Ghislain MARY committed
676
	MSSndCardManager *manager = ms_factory_get_snd_card_manager(factory);
677
	ms_snd_card_manager_register_desc(manager, &ms_wasapi_snd_card_desc);
678 679
	ms_message("libmswasapi plugin loaded");
}