Debian Codegraph @

Xpjproject/pjmedia/src/pjmedia-audiodev/wasapi_dev.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18 #include <pjmedia-audiodev/audiodev_imp.h>
19 #include <pj/assert.h>
20 #include <pj/log.h>
21 #include <pj/os.h>
22
23 #if PJMEDIA_AUDIO_DEV_HAS_WASAPI
24
25 #include <Avrt.h>
26 #include <windows.h>
27 #include <audioclient.h>
28 #include <Processthreadsapi.h>
29
30 #if defined(PJ_WIN32_UWP) && PJ_WIN32_UWP
31 #define USE_ASYNC_ACTIVATE 1;
32 #endif
33
34 #if defined(USE_ASYNC_ACTIVATE)
35 #include <Mmdeviceapi.h>
36 #include <wrl\implements.h>
37 #include <ppltasks.h>
38 using namespace Windows::Media::Devices;
39 using namespace Microsoft::WRL;
40 using namespace concurrency;
41 #else
42 #include <phoneaudioclient.h>
43 #using <Windows.winmd>
44 using namespace Windows::Phone::Media::Devices;
45 #endif
46
47 #define THIS_FILE "wasapi_dev.cpp"
48
49 /* Set to 1 to enable tracing */
50 #if 1
51 # define TRACE_(expr) PJ_LOG(4,expr)
52 #else
53 # define TRACE_(expr)
54 #endif
55
56 #define EXIT_ON_ERROR(hr) \
57 do { \
58 if(FAILED(hr)) { \
59 status = PJMEDIA_EAUD_WASAPI_ERROR; \
60 goto on_exit; }\
61 } while (0)
62
63 struct wasapi_stream;
64
65 class AudioActivator;
66
67 #if defined(USE_ASYNC_ACTIVATE)
68
69 class AudioActivator : public RuntimeClass< RuntimeClassFlags< ClassicCom >,
70 FtmBase,
71 IActivateAudioInterfaceCompletionHandler >
72 {
73 STDMETHODIMP ActivateCompleted(IActivateAudioInterfaceAsyncOperation
74 *pAsyncOp);
75 public:
76 AudioActivator() {};
77 task_completion_event<ComPtr<IAudioClient2>> task_completed;
78 };
79
80 #endif
81
82 /* WASAPI factory */
83 struct wasapi_factory
84 {
85 pjmedia_aud_dev_factory base;
86 pj_pool_t *base_pool;
87 pj_pool_t *pool;
88 pj_pool_factory *pf;
89
90 unsigned dev_count;
91 pjmedia_aud_dev_info devs[1];
92 };
93
94 /* Sound stream. */
95 struct wasapi_stream
96 {
97 pjmedia_aud_stream base; /* Base stream */
98
99 /* Common */
100 pjmedia_aud_param param; /* Settings */
101 pj_pool_t *pool; /* Memory pool */
102 void *user_data; /* Application data */
103 struct wasapi_factory *wf;
104 pj_thread_t *thread; /* Thread handle */
105 HANDLE quit_event;
106 pjmedia_format_id fmt_id; /* Frame format */
107 unsigned bytes_per_sample;
108
109 /* Playback */
110 pjmedia_aud_play_cb pb_cb; /* Playback callback */
111 IAudioClient2 *default_pb_dev; /* Default playback dev */
112 IAudioRenderClient *pb_client; /* Playback client */
113 ISimpleAudioVolume *pb_volume; /* Playback volume */
114 unsigned pb_max_frame_count;
115 HANDLE pb_event; /* Playback event */
116 pj_timestamp pb_timestamp;
117 #if defined(USE_ASYNC_ACTIVATE)
118 ComPtr<AudioActivator> pb_aud_act;
119 Platform::String^ pb_id;
120 #else
121 LPCWSTR pb_id;
122 #endif
123
124 /* Capture */
125 pjmedia_aud_rec_cb cap_cb; /* Capture callback */
126 IAudioClient2 *default_cap_dev; /* Default capture dev */
127 IAudioCaptureClient *cap_client; /* Capture client */
128 unsigned bytes_per_frame; /* Bytes per frame */
129 pj_int16_t *cap_buf; /* Capture audio buffer */
130 unsigned cap_max_frame_count;
131 HANDLE cap_event; /* Capture event */
132 unsigned cap_buf_count;
133 pj_timestamp cap_timestamp;
134 #if defined(USE_ASYNC_ACTIVATE)
135 ComPtr<AudioActivator> cap_aud_act;
136 Platform::String^ cap_id;
137 #else
138 LPCWSTR cap_id;
139 #endif
140 };
141
142 /* Prototypes */
143 static pj_status_t wasapi_factory_init(pjmedia_aud_dev_factory *f);
144 static pj_status_t wasapi_factory_destroy(pjmedia_aud_dev_factory *f);
145 static pj_status_t wasapi_factory_refresh(pjmedia_aud_dev_factory *f);
146 static unsigned wasapi_factory_get_dev_count(pjmedia_aud_dev_factory *f);
147 static pj_status_t wasapi_factory_get_dev_info(pjmedia_aud_dev_factory *f,
148 unsigned index,
149 pjmedia_aud_dev_info *info);
150 static pj_status_t wasapi_factory_default_param(pjmedia_aud_dev_factory *f,
151 unsigned index,
152 pjmedia_aud_param *param);
153 static pj_status_t wasapi_factory_create_stream(pjmedia_aud_dev_factory *f,
154 const pjmedia_aud_param *param,
155 pjmedia_aud_rec_cb rec_cb,
156 pjmedia_aud_play_cb play_cb,
157 void *user_data,
158 pjmedia_aud_stream **p_strm);
159
160 /*
161 * Stream prototypes
162 */
163 static pj_status_t wasapi_stream_get_param(pjmedia_aud_stream *strm,
164 pjmedia_aud_param *param);
165 static pj_status_t wasapi_stream_get_cap(pjmedia_aud_stream *strm,
166 pjmedia_aud_dev_cap cap,
167 void *value);
168 static pj_status_t wasapi_stream_set_cap(pjmedia_aud_stream *strm,
169 pjmedia_aud_dev_cap cap,
170 const void *value);
171 static pj_status_t wasapi_stream_start(pjmedia_aud_stream *strm);
172 static pj_status_t wasapi_stream_stop(pjmedia_aud_stream *strm);
173 static pj_status_t wasapi_stream_destroy(pjmedia_aud_stream *strm);
174
175 /* Operations */
176 static pjmedia_aud_dev_factory_op factory_op =
177 {
178 &wasapi_factory_init,
179 &wasapi_factory_destroy,
180 &wasapi_factory_get_dev_count,
181 &wasapi_factory_get_dev_info,
182 &wasapi_factory_default_param,
183 &wasapi_factory_create_stream,
184 &wasapi_factory_refresh
185 };
186
187 static pjmedia_aud_stream_op stream_op =
188 {
189 &wasapi_stream_get_param,
190 &wasapi_stream_get_cap,
191 &wasapi_stream_set_cap,
192 &wasapi_stream_start,
193 &wasapi_stream_stop,
194 &wasapi_stream_destroy
195 };
196
197 static pj_status_t init_waveformatex(WAVEFORMATEX *wfx,
198 const pjmedia_aud_param *prm,
199 struct wasapi_stream *strm)
200 {
201 if (prm->ext_fmt.id == PJMEDIA_FORMAT_L16) {
202 wfx->wFormatTag = WAVE_FORMAT_PCM;
203 wfx->nChannels = (pj_uint16_t)prm->channel_count;
204 wfx->nSamplesPerSec = prm->clock_rate;
205 wfx->nBlockAlign = (pj_uint16_t)(prm->channel_count *
206 strm->bytes_per_sample);
207 wfx->nAvgBytesPerSec = prm->clock_rate * prm->channel_count *
208 strm->bytes_per_sample;
209 wfx->wBitsPerSample = (WORD)prm->bits_per_sample;
210 wfx->cbSize = 0;
211
212 return PJ_SUCCESS;
213 }
214 else if ((prm->flags & PJMEDIA_AUD_DEV_CAP_EXT_FORMAT) &&
215 (prm->ext_fmt.id == PJMEDIA_FORMAT_PCMA ||
216 prm->ext_fmt.id == PJMEDIA_FORMAT_PCMU))
217 {
218 unsigned ptime;
219 ptime = prm->samples_per_frame * 1000 /
220 (prm->clock_rate * prm->channel_count);
221 wfx->wFormatTag = (pj_uint16_t)
222 ((prm->ext_fmt.id == PJMEDIA_FORMAT_PCMA) ?
223 WAVE_FORMAT_ALAW : WAVE_FORMAT_MULAW);
224 wfx->nChannels = (pj_uint16_t)prm->channel_count;
225 wfx->nSamplesPerSec = prm->clock_rate;
226 wfx->nAvgBytesPerSec = prm->clock_rate * prm->channel_count;
227 wfx->nBlockAlign = (pj_uint16_t)(wfx->nAvgBytesPerSec * ptime /
228 1000);
229 wfx->wBitsPerSample = 8;
230 wfx->cbSize = 0;
231
232 return PJ_SUCCESS;
233 } else {
234 return PJMEDIA_EAUD_BADFORMAT;
235 }
236 }
237
238 /* WMME capture and playback thread. */
239 static int PJ_THREAD_FUNC wasapi_dev_thread(void *arg)
240 {
241 struct wasapi_stream *strm = (struct wasapi_stream*)arg;
242 HANDLE events[3];
243 unsigned eventCount;
244 pj_status_t status = PJ_SUCCESS;
245 static unsigned rec_cnt, play_cnt;
246 enum { MAX_BURST = 1000 };
247
248 rec_cnt = play_cnt = 0;
249 strm->cap_buf_count = 0;
250 eventCount = 0;
251 events[eventCount++] = strm->quit_event;
252 if (strm->param.dir & PJMEDIA_DIR_PLAYBACK)
253 events[eventCount++] = strm->pb_event;
254 if (strm->param.dir & PJMEDIA_DIR_CAPTURE)
255 events[eventCount++] = strm->cap_event;
256
257 /*
258 * Loop while not signalled to quit, wait for event objects to be
259 * signalled by Wasapi capture and play buffer.
260 */
261 while (status == PJ_SUCCESS)
262 {
263 DWORD rc;
264 pjmedia_dir signalled_dir;
265 HRESULT hr;
266
267 /* Swap hWaveIn and hWaveOut to get equal opportunity for both */
268 if (eventCount==3) {
269 HANDLE hTemp = events[2];
270 events[2] = events[1];
271 events[1] = hTemp;
272 }
273
274 rc = WaitForMultipleObjectsEx(eventCount, events, FALSE, INFINITE,
275 FALSE);
276
277 if (rc < WAIT_OBJECT_0 || rc >= WAIT_OBJECT_0 + eventCount)
278 continue;
279
280 if (rc == WAIT_OBJECT_0)
281 break;
282
283 if (rc == (WAIT_OBJECT_0 + 1)) {
284 if (events[1] == strm->pb_event)
285 signalled_dir = PJMEDIA_DIR_PLAYBACK;
286 else
287 signalled_dir = PJMEDIA_DIR_CAPTURE;
288 } else {
289 if (events[2] == strm->pb_event)
290 signalled_dir = PJMEDIA_DIR_PLAYBACK;
291 else
292 signalled_dir = PJMEDIA_DIR_CAPTURE;
293 }
294
295 if (signalled_dir == PJMEDIA_DIR_PLAYBACK) {
296 unsigned incoming_frame = 0;
297 unsigned frame_to_render = 0;
298 unsigned padding = 0;
299 BYTE *cur_pb_buf = NULL;
300 pjmedia_frame frame;
301
302 status = PJ_SUCCESS;
303
304 /* Get available space on buffer to render */
305 hr = strm->default_pb_dev->GetCurrentPadding(&padding);
306 if (FAILED(hr)) {
307 continue;
308 }
309
310 incoming_frame = strm->bytes_per_frame /
311 (strm->bytes_per_sample *
312 strm->param.channel_count);
313 frame_to_render = strm->pb_max_frame_count - padding;
314 if (frame_to_render >= incoming_frame) {
315 frame_to_render = incoming_frame;
316 } else {
317 /* Don't get new frame because there's no space */
318 continue;
319 }
320
321 hr = strm->pb_client->GetBuffer(frame_to_render, &cur_pb_buf);
322 if (FAILED(hr)) {
323 PJ_LOG(4, (THIS_FILE, "Error getting wasapi buffer"));
324 continue;
325 }
326
327 if (strm->fmt_id == PJMEDIA_FORMAT_L16) {
328 /* PCM mode */
329 frame.type = PJMEDIA_FRAME_TYPE_AUDIO;
330 frame.size = strm->bytes_per_frame;
331 frame.timestamp.u64 = strm->pb_timestamp.u64;
332 frame.bit_info = 0;
333 frame.buf = cur_pb_buf;
334 }
335
336 status = (*strm->pb_cb)(strm->user_data, &frame);
337
338 /* Write to the device. */
339 hr = strm->pb_client->ReleaseBuffer(frame_to_render, 0);
340 if (FAILED(hr)) {
341 PJ_LOG(4, (THIS_FILE, "Error releasing wasapi buffer"));
342 continue;
343 }
344
345 strm->pb_timestamp.u64 += strm->param.samples_per_frame /
346 strm->param.channel_count;
347 } else {
348 /* Capture */
349 pj_uint32_t packet_size = 0;
350
351 hr = strm->cap_client->GetNextPacketSize(&packet_size);
352 if (FAILED(hr)) {
353 PJ_LOG(4, (THIS_FILE, "Error getting next packet size"));
354 continue;
355 }
356
357 while (packet_size) {
358
359 unsigned next_frame_size = 0;
360 DWORD cap_flag;
361 pj_int16_t *cap_buf = NULL;
362 unsigned nsamples = 0;
363
364 hr = strm->cap_client->GetBuffer((BYTE**)&cap_buf,
365 &next_frame_size,
366 &cap_flag,
367 NULL,
368 NULL);
369
370 if (FAILED(hr) || (next_frame_size == 0)) {
371 PJ_LOG(4, (THIS_FILE, "Error getting next buffer, \
372 next frame size : %d", next_frame_size));
373 packet_size = 0;
374 continue;
375 }
376
377 nsamples = (next_frame_size * strm->param.channel_count)
378 + strm->cap_buf_count;
379
380 if (nsamples >= strm->param.samples_per_frame) {
381 /* If buffer is not empty, combine the buffer with the just
382 * incoming samples, then call put_frame.
383 */
384 if (strm->cap_buf_count) {
385 unsigned chunk_count = 0;
386 pjmedia_frame frame;
387
388 chunk_count = strm->param.samples_per_frame -
389 strm->cap_buf_count;
390
391 pjmedia_copy_samples(strm->cap_buf +
392 strm->cap_buf_count,
393 (pj_int16_t*)cap_buf,
394 chunk_count);
395
396 if (strm->fmt_id == PJMEDIA_FORMAT_L16) {
397 /* PCM mode */
398 /* Prepare frame */
399 frame.type = PJMEDIA_FRAME_TYPE_AUDIO;
400 frame.buf = (void *)strm->cap_buf;
401 frame.size = strm->bytes_per_frame;
402 frame.timestamp.u64 = strm->cap_timestamp.u64;
403 frame.bit_info = 0;
404 }
405
406 status = (*strm->cap_cb)(strm->user_data, &frame);
407 if (status == PJ_SUCCESS) {
408 /* Update position */
409 cap_buf = (pj_int16_t *)cap_buf + chunk_count;
410 nsamples -= strm->param.samples_per_frame;
411 strm->cap_timestamp.u64 +=
412 strm->param.samples_per_frame /
413 strm->param.channel_count;
414 }
415 }
416
417 /* Give all frame we have */
418 while (nsamples >= strm->param.samples_per_frame &&
419 status == PJ_SUCCESS)
420 {
421 pjmedia_frame frame;
422
423 pjmedia_copy_samples(strm->cap_buf,
424 (pj_int16_t*)cap_buf,
425 strm->param.samples_per_frame);
426
427 if (strm->fmt_id == PJMEDIA_FORMAT_L16) {
428 /* PCM mode */
429 /* Prepare frame */
430 frame.type = PJMEDIA_FRAME_TYPE_AUDIO;
431 frame.buf = (void *)strm->cap_buf;
432 frame.size = strm->bytes_per_frame;
433 frame.timestamp.u64 = strm->cap_timestamp.u64;
434 frame.bit_info = 0;
435 }
436 status = (*strm->cap_cb)(strm->user_data, &frame);
437
438 if (status == PJ_SUCCESS) {
439 /* Update position */
440 cap_buf = (pj_int16_t *)cap_buf +
441 strm->param.samples_per_frame;
442
443 nsamples -= strm->param.samples_per_frame;
444 strm->cap_timestamp.u64 +=
445 strm->param.samples_per_frame /
446 strm->param.channel_count;
447 } else {
448 nsamples = 0;
449 }
450 }
451 strm->cap_buf_count = nsamples;
452
453 /* Store the remaining samples into the buffer */
454 if (nsamples && (status == PJ_SUCCESS)) {
455 pjmedia_copy_samples(strm->cap_buf,
456 (pj_int16_t*)cap_buf,
457 nsamples);
458 }
459 } else {
460 /* Not enough samples, let's just store them in the
461 * buffer.
462 */
463 pjmedia_copy_samples(strm->cap_buf + strm->cap_buf_count,
464 (pj_int16_t*)cap_buf,
465 next_frame_size *
466 strm->param.channel_count);
467
468 strm->cap_buf_count = nsamples;
469 }
470 hr = strm->cap_client->ReleaseBuffer(next_frame_size);
471
472 hr = strm->cap_client->GetNextPacketSize(&packet_size);
473 if (FAILED(hr)) {
474 PJ_LOG(4, (THIS_FILE, "Error getting next packet size"));
475 packet_size = 0;
476 }
477 }
478 }
479 }
480
481 PJ_LOG(5,(THIS_FILE, "WASAPI: thread stopping.."));
482 return 0;
483 }
484
485 static pj_status_t activate_capture_dev(struct wasapi_stream *ws)
486 {
487 HRESULT hr = E_FAIL;
488
489 #if defined(USE_ASYNC_ACTIVATE)
490 ComPtr<IActivateAudioInterfaceAsyncOperation> async_op;
491 ws->cap_id = MediaDevice::GetDefaultAudioCaptureId(
492 AudioDeviceRole::Communications);
493 #else
494 ws->cap_id = GetDefaultAudioCaptureId(AudioDeviceRole::Communications);
495 #endif
496
497 if (!ws->cap_id) {
498 PJ_LOG(4, (THIS_FILE, "Error getting default capture device id"));
499 return PJMEDIA_EAUD_SYSERR;
500 }
501
502 #if defined(USE_ASYNC_ACTIVATE)
503
504 ws->cap_aud_act = Make<AudioActivator>();
505 if (ws->cap_aud_act == NULL) {
506 PJ_LOG(4, (THIS_FILE, "Error activating capture device"));
507 return PJMEDIA_EAUD_SYSERR;
508 }
509 hr = ActivateAudioInterfaceAsync(ws->cap_id->Data(),
510 __uuidof(IAudioClient2),
511 NULL, ws->cap_aud_act.Get(),
512 &async_op);
513
514 //pj_thread_sleep(100);
515 auto task_completed = create_task(ws->cap_aud_act->task_completed);
516 task_completed.wait();
517 ws->default_cap_dev = task_completed.get().Get();
518 #else
519 hr = ActivateAudioInterface(ws->cap_id, __uuidof(IAudioClient2),
520 (void**)&ws->default_cap_dev);
521 #endif
522 AudioClientProperties properties = {};
523 if (SUCCEEDED(hr))
524 {
525 properties.cbSize = sizeof AudioClientProperties;
526 properties.eCategory = AudioCategory_Communications;
527 hr = ws->default_cap_dev->SetClientProperties(&properties);
528 }
529
530 return FAILED(hr) ? PJMEDIA_EAUD_SYSERR : PJ_SUCCESS;
531 }
532
533 /*
534 * Init capture device
535 */
536 static pj_status_t init_capture_dev(struct wasapi_stream *ws,
537 const pjmedia_aud_param *prm)
538 {
539 pj_status_t status;
540 HRESULT hr = E_FAIL;
541 REFERENCE_TIME request_duration = 0;
542 unsigned ptime;
543 unsigned int stream_flags;
544 WAVEFORMATEX wfx;
545 int test;
546
547 status = activate_capture_dev(ws);
548 if (status != PJ_SUCCESS) {
549 PJ_LOG(4, (THIS_FILE, "Failed activating capture device"));
550 goto on_exit;
551 }
552
553 stream_flags = 0x88140000;
554
555 pj_bzero(&wfx, sizeof(WAVEFORMATEX));
556 status = init_waveformatex(&wfx, prm, ws);
557
558 if (status != PJ_SUCCESS) {
559 PJ_LOG(4, (THIS_FILE, "Error initiating wave format"));
560 goto on_exit;
561 }
562 status = PJMEDIA_EAUD_SYSERR;
563
564 ptime = prm->samples_per_frame * 1000 /
565 (prm->clock_rate * prm->channel_count);
566
567 ws->bytes_per_frame = prm->samples_per_frame * ws->bytes_per_sample;
568
569 /* Initialize the stream to play at the minimum latency. */
570 hr = ws->default_cap_dev->GetDevicePeriod(NULL, &request_duration);
571
572 EXIT_ON_ERROR(hr);
573
574 test = ws->param.input_latency_ms * 10000;
575
576 hr = ws->default_cap_dev->Initialize(AUDCLNT_SHAREMODE_SHARED,
577 stream_flags,
578 //2000 * 10000,
579 ptime * ws->param.input_latency_ms *
580 10000,
581 0,
582 &wfx,
583 NULL);
584
585 EXIT_ON_ERROR(hr);
586
587 ws->cap_buf = (pj_int16_t *)pj_pool_zalloc(ws->pool, ws->bytes_per_frame);
588
589 if (!ws->cap_buf) {
590 PJ_LOG(4, (THIS_FILE, "Error creating capture buffer"));
591 status = PJ_ENOMEM;
592
593 goto on_exit;
594 }
595
596 ws->cap_event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
597 if (!ws->cap_event) {
598 hr = HRESULT_FROM_WIN32(GetLastError());
599
600 goto on_exit;
601 }
602
603 EXIT_ON_ERROR(hr);
604
605 hr = ws->default_cap_dev->SetEventHandle(ws->cap_event);
606
607 EXIT_ON_ERROR(hr);
608
609 hr = ws->default_cap_dev->GetService(__uuidof(IAudioCaptureClient),
610 (void**)&ws->cap_client);
611
612 EXIT_ON_ERROR(hr);
613
614 PJ_LOG(4, (THIS_FILE,
615 "Wasapi Sound recorder initialized ("
616 "clock_rate=%d, latency=%d, "
617 "channel_count=%d, samples_per_frame=%d (%dms))",
618 prm->clock_rate, ws->param.input_latency_ms,
619 prm->channel_count, prm->samples_per_frame,
620 ptime));
621
622 status = PJ_SUCCESS;
623 on_exit:
624 if (status != PJ_SUCCESS)
625 wasapi_stream_destroy(&ws->base);
626
627 return status;
628 }
629
630 static pj_status_t activate_playback_dev(struct wasapi_stream *ws)
631 {
632 HRESULT hr = E_FAIL;
633
634 #if defined(USE_ASYNC_ACTIVATE)
635 ComPtr<IActivateAudioInterfaceAsyncOperation> async_op;
636
637 ws->pb_id = MediaDevice::GetDefaultAudioRenderId(
638 AudioDeviceRole::Communications);
639 #else
640 ws->pb_id = GetDefaultAudioRenderId(AudioDeviceRole::Communications);
641 #endif
642
643 if (!ws->pb_id) {
644 PJ_LOG(4, (THIS_FILE, "Error getting default playback device id"));
645 return PJMEDIA_EAUD_SYSERR;
646 }
647
648 #if defined(USE_ASYNC_ACTIVATE)
649 ws->pb_aud_act = Make<AudioActivator>();
650 if (ws->pb_aud_act == NULL) {
651 PJ_LOG(4, (THIS_FILE, "Error activating playback device"));
652 return PJMEDIA_EAUD_SYSERR;
653 }
654 hr = ActivateAudioInterfaceAsync(ws->pb_id->Data(),
655 __uuidof(IAudioClient2),
656 NULL, ws->pb_aud_act.Get(),
657 &async_op);
658
659 //pj_thread_sleep(100);
660 auto task_completed = create_task(ws->pb_aud_act->task_completed);
661 task_completed.wait();
662 ws->default_pb_dev = task_completed.get().Get();
663 #else
664 hr = ActivateAudioInterface(ws->pb_id, __uuidof(IAudioClient2),
665 (void**)&ws->default_pb_dev);
666 #endif
667
668 AudioClientProperties properties = {};
669 if (SUCCEEDED(hr))
670 {
671 properties.cbSize = sizeof AudioClientProperties;
672 properties.eCategory = AudioCategory_Communications;
673 hr = ws->default_pb_dev->SetClientProperties(&properties);
674 }
675
676 return FAILED(hr) ? PJMEDIA_EAUD_SYSERR : PJ_SUCCESS;
677 }
678
679 /*
680 * Init playback device
681 */
682 static pj_status_t init_playback_dev(struct wasapi_stream *ws,
683 const pjmedia_aud_param *prm)
684 {
685 HRESULT hr = E_FAIL;
686 pj_status_t status;
687 unsigned ptime;
688 unsigned int stream_flags;
689 WAVEFORMATEX wfx;
690
691 status = activate_playback_dev(ws);
692 if (status != PJ_SUCCESS) {
693 PJ_LOG(4, (THIS_FILE, "Failed activating playback device"));
694 goto on_exit;
695 }
696
697 stream_flags = 0x88140000;
698 pj_bzero(&wfx, sizeof(WAVEFORMATEX));
699
700 status = init_waveformatex(&wfx, prm, ws);
701 if (status != PJ_SUCCESS) {
702 PJ_LOG(4, (THIS_FILE, "Error initiating wave format"));
703
704 goto on_exit;
705 }
706 status = PJMEDIA_EAUD_SYSERR;
707
708 ptime = prm->samples_per_frame * 1000 /
709 (prm->clock_rate * prm->channel_count);
710
711 ws->bytes_per_frame = prm->samples_per_frame * ws->bytes_per_sample;
712
713 hr = ws->default_pb_dev->Initialize(AUDCLNT_SHAREMODE_SHARED,
714 stream_flags,
715 ws->param.output_latency_ms * 10000,
716 //0,
717 0,
718 &wfx,
719 NULL);
720
721 EXIT_ON_ERROR(hr);
722
723 hr = ws->default_pb_dev->GetBufferSize(&ws->pb_max_frame_count);
724
725 /* Create buffer */
726 EXIT_ON_ERROR(hr);
727
728 ws->pb_event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
729 if (!ws->pb_event) {
730 hr = HRESULT_FROM_WIN32(GetLastError());
731
732 goto on_exit;
733 }
734
735 EXIT_ON_ERROR(hr);
736
737 hr = ws->default_pb_dev->SetEventHandle(ws->pb_event);
738
739 EXIT_ON_ERROR(hr);
740
741 hr = ws->default_pb_dev->GetService(__uuidof(IAudioRenderClient),
742 (void**)&ws->pb_client);
743
744 EXIT_ON_ERROR(hr);
745
746 /* Other/optional supported interfaces */
747 hr = ws->default_pb_dev->GetService(__uuidof(ISimpleAudioVolume),
748 (void**)&ws->pb_volume);
749
750 if (FAILED(hr)) {
751 PJ_LOG(4, (THIS_FILE, "Error getting vol service playback:0x%x", hr));
752 }
753
754 PJ_LOG(4, (THIS_FILE,
755 " Wasapi Sound player initialized ("
756 "clock_rate=%d, latency=%d, "
757 "channel_count=%d, samples_per_frame=%d (%dms))",
758 prm->clock_rate, ws->param.output_latency_ms,
759 prm->channel_count, prm->samples_per_frame,
760 ptime));
761
762 status = PJ_SUCCESS;
763 on_exit:
764 if (status != PJ_SUCCESS)
765 wasapi_stream_destroy(&ws->base);
766
767 return status;
768 }
769
770 /*
771 * wasapi - tests loads the audio units and sets up the driver structure
772 */
773 static pj_status_t wasapi_add_dev(struct wasapi_factory *wf)
774 {
775 pjmedia_aud_dev_info *adi;
776 LPCWSTR capture_id = NULL;
777 LPCWSTR render_id = NULL;
778
779 if (wf->dev_count >= PJ_ARRAY_SIZE(wf->devs))
780 return PJ_ETOOMANY;
781
782 adi = &wf->devs[wf->dev_count];
783
784 /* Reset device info */
785 pj_bzero(adi, sizeof(*adi));
786
787 /* Set device name */
788 pj_ansi_strxcpy(adi->name, "default", sizeof(adi->name));
789 pj_ansi_strxcpy(adi->driver, "wasapi", sizeof(adi->driver));
790
791 /* Get default capture device */
792 #if defined(USE_ASYNC_ACTIVATE)
793 capture_id = MediaDevice::GetDefaultAudioCaptureId(
794 AudioDeviceRole::Communications)->Data();
795 #else
796 capture_id = GetDefaultAudioCaptureId(AudioDeviceRole::Communications);
797 #endif
798
799 if (!capture_id) {
800 PJ_LOG(4, (THIS_FILE, "Failed to get default audio capture"));
801 }
802
803 /* Get default render device */
804 #if defined(USE_ASYNC_ACTIVATE)
805 render_id = MediaDevice::GetDefaultAudioRenderId(
806 AudioDeviceRole::Communications)->Data();
807 #else
808 render_id = GetDefaultAudioRenderId(AudioDeviceRole::Communications);
809 #endif
810
811 if (!render_id) {
812 PJ_LOG(4, (THIS_FILE, "Failed to get default audio render"));
813 }
814
815 if (!capture_id && !render_id) {
816 PJ_LOG(4, (THIS_FILE, "Unable to open default sound device"));
817 return PJMEDIA_EAUD_NODEV;
818 }
819
820 /* Check the number of capture channels */
821 adi->input_count = (capture_id) ? 1 : 0;
822
823 /* Check the number of playback channels */
824 adi->output_count = (render_id) ? 1 : 0;
825
826 /* Set the default sample rate */
827 adi->default_samples_per_sec = 8000;
828
829 adi->caps = PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY |
830 PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY |
831 PJMEDIA_AUD_DEV_CAP_OUTPUT_ROUTE;
832
833 adi->routes = PJMEDIA_AUD_DEV_ROUTE_DEFAULT |
834 PJMEDIA_AUD_DEV_ROUTE_EARPIECE |
835 PJMEDIA_AUD_DEV_ROUTE_LOUDSPEAKER |
836 PJMEDIA_AUD_DEV_ROUTE_BLUETOOTH;
837
838 ++wf->dev_count;
839
840 PJ_LOG(4, (THIS_FILE, "Added sound device %s", adi->name));
841
842 #if !defined(USE_ASYNC_ACTIVATE)
843 if (capture_id)
844 CoTaskMemFree((LPVOID*)capture_id);
845
846 if (render_id)
847 CoTaskMemFree((LPVOID*)render_id);
848 #endif
849
850 return PJ_SUCCESS;
851 }
852
853 /****************************************************************************
854 * Factory operations
855 */
856 /*
857 * Init wasapi audio driver.
858 */
859
860 #ifdef __cplusplus
861 extern "C"{
862 #endif
863 pjmedia_aud_dev_factory* pjmedia_wasapi_factory(pj_pool_factory *pf)
864 {
865 struct wasapi_factory *wf;
866 pj_pool_t *pool;
867
868 pool = pj_pool_create(pf, "WASAPI base", 256, 256, NULL);
869 wf = PJ_POOL_ZALLOC_T(pool, struct wasapi_factory);
870 wf->pf = pf;
871 wf->base_pool = pool;
872 wf->base.op = &factory_op;
873
874 return &wf->base;
875 }
876 #ifdef __cplusplus
877 }
878 #endif
879
880 /* API: init factory */
881 static pj_status_t wasapi_factory_init(pjmedia_aud_dev_factory *f)
882 {
883 pj_status_t status;
884 status = wasapi_factory_refresh(f);
885 if (status != PJ_SUCCESS)
886 return status;
887
888 PJ_LOG(4,(THIS_FILE, "wasapi initialized"));
889 return PJ_SUCCESS;
890 }
891
892 /* API: destroy factory */
893 static pj_status_t wasapi_factory_destroy(pjmedia_aud_dev_factory *f)
894 {
895 struct wasapi_factory *wf = (struct wasapi_factory*)f;
896
897 if (wf->pool) {
898 TRACE_((THIS_FILE, "wasapi_factory_destroy()"));
899 pj_pool_release(wf->pool);
900 }
901
902 return PJ_SUCCESS;
903 }
904
905 /* API: refresh the list of devices */
906 static pj_status_t wasapi_factory_refresh(pjmedia_aud_dev_factory *f)
907 {
908 struct wasapi_factory *wf = (struct wasapi_factory*)f;
909 pj_status_t status;
910
911 TRACE_((THIS_FILE, "wasapi_factory_refresh()"));
912
913 if (wf->pool != NULL) {
914 pj_pool_release(wf->pool);
915 wf->pool = NULL;
916 }
917
918 wf->pool = pj_pool_create(wf->pf, "wasapi_aud", 256, 256, NULL);
919 wf->dev_count = 0;
920
921 status = wasapi_add_dev(wf);
922
923 PJ_LOG(4,(THIS_FILE, "wasapi driver found %d devices", wf->dev_count));
924
925 return status;
926 }
927
928 /* API: get number of devices */
929 static unsigned wasapi_factory_get_dev_count(pjmedia_aud_dev_factory *f)
930 {
931 struct wasapi_factory *wf = (struct wasapi_factory*)f;
932 return wf->dev_count;
933 }
934
935 /* API: get device info */
936 static pj_status_t wasapi_factory_get_dev_info(pjmedia_aud_dev_factory *f,
937 unsigned index,
938 pjmedia_aud_dev_info *info)
939 {
940 struct wasapi_factory *wf = (struct wasapi_factory*)f;
941
942 PJ_ASSERT_RETURN(index>=0 && index<wf->dev_count, PJ_EINVAL);
943
944 pj_memcpy(info, &wf->devs[index], sizeof(*info));
945
946 return PJ_SUCCESS;
947 }
948
949 /* API: create default device parameter */
950 static pj_status_t wasapi_factory_default_param(pjmedia_aud_dev_factory *f,
951 unsigned index,
952 pjmedia_aud_param *param)
953 {
954 struct wasapi_factory *wf = (struct wasapi_factory*)f;
955 struct pjmedia_aud_dev_info *di;
956
957 PJ_ASSERT_RETURN(index>=0 && index<wf->dev_count, PJ_EINVAL);
958
959 di = &wf->devs[index];
960
961 pj_bzero(param, sizeof(*param));
962 if (di->input_count && di->output_count) {
963 param->dir = PJMEDIA_DIR_CAPTURE_PLAYBACK;
964 param->rec_id = index;
965 param->play_id = index;
966 } else if (di->input_count) {
967 param->dir = PJMEDIA_DIR_CAPTURE;
968 param->rec_id = index;
969 param->play_id = PJMEDIA_AUD_INVALID_DEV;
970 } else if (di->output_count) {
971 param->dir = PJMEDIA_DIR_PLAYBACK;
972 param->play_id = index;
973 param->rec_id = PJMEDIA_AUD_INVALID_DEV;
974 } else {
975 return PJMEDIA_EAUD_INVDEV;
976 }
977
978 /* Set the mandatory settings here */
979 /* The values here are just some examples */
980 param->clock_rate = di->default_samples_per_sec;
981 param->channel_count = 2;
982 param->samples_per_frame = di->default_samples_per_sec * 20 / 1000;
983 param->bits_per_sample = 32;
984 param->flags = di->caps;
985 param->input_latency_ms = PJMEDIA_SND_DEFAULT_REC_LATENCY;
986 param->output_latency_ms = PJMEDIA_SND_DEFAULT_PLAY_LATENCY;
987
988 TRACE_((THIS_FILE, "wasapi_factory_default_param clock = %d flags = %d"
989 " spf = %d", param->clock_rate, param->flags,
990 param->samples_per_frame));
991
992 return PJ_SUCCESS;
993 }
994
995 /* API: create stream */
996 static pj_status_t wasapi_factory_create_stream(pjmedia_aud_dev_factory *f,
997 const pjmedia_aud_param *param,
998 pjmedia_aud_rec_cb rec_cb,
999 pjmedia_aud_play_cb play_cb,
1000 void *user_data,
1001 pjmedia_aud_stream **p_strm)
1002 {
1003 struct wasapi_factory *wf = (struct wasapi_factory*)f;
1004 pj_pool_t *pool;
1005 struct wasapi_stream *strm;
1006 pj_status_t status;
1007
1008 /* Create and Initialize stream descriptor */
1009 pool = pj_pool_create(wf->pf, "wasapi-dev", 1024, 1024, NULL);
1010 PJ_ASSERT_RETURN(pool != NULL, PJ_ENOMEM);
1011
1012 strm = PJ_POOL_ZALLOC_T(pool, struct wasapi_stream);
1013 pj_memcpy(&strm->param, param, sizeof(*param));
1014 strm->base.op = &stream_op;
1015 strm->pool = pool;
1016 strm->cap_cb = rec_cb;
1017 strm->pb_cb = play_cb;
1018 strm->fmt_id = (pjmedia_format_id)param->ext_fmt.id;
1019 strm->user_data = user_data;
1020 strm->bytes_per_sample = param->bits_per_sample / 8;
1021
1022 /* Init capture */
1023 if (param->dir & PJMEDIA_DIR_CAPTURE) {
1024 status = init_capture_dev(strm, param);
1025 if (status != PJ_SUCCESS) {
1026 wasapi_stream_destroy(&strm->base);
1027 return status;
1028 }
1029 }
1030 /* Init playback */
1031 if (param->dir & PJMEDIA_DIR_PLAYBACK) {
1032 status = init_playback_dev(strm, param);
1033 if (status != PJ_SUCCESS) {
1034 wasapi_stream_destroy(&strm->base);
1035 return status;
1036 }
1037 }
1038
1039 strm->quit_event = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
1040 EVENT_ALL_ACCESS);
1041 if (!strm->quit_event)
1042 {
1043 PJ_LOG(4, (THIS_FILE, "Error creating quit event:0x%x",
1044 HRESULT_FROM_WIN32(GetLastError())));
1045
1046 return PJMEDIA_EAUD_SYSERR;
1047 }
1048
1049 /* Done */
1050 strm->base.op = &stream_op;
1051 *p_strm = &strm->base;
1052
1053 return PJ_SUCCESS;
1054 }
1055
1056 /* API: Get stream info. */
1057 static pj_status_t wasapi_stream_get_param(pjmedia_aud_stream *s,
1058 pjmedia_aud_param *pi)
1059 {
1060 struct wasapi_stream *strm = (struct wasapi_stream*)s;
1061
1062 PJ_ASSERT_RETURN(strm && pi, PJ_EINVAL);
1063
1064 pj_memcpy(pi, &strm->param, sizeof(*pi));
1065
1066 return PJ_SUCCESS;
1067 }
1068
1069 /* API: get capability */
1070 static pj_status_t wasapi_stream_get_cap(pjmedia_aud_stream *s,
1071 pjmedia_aud_dev_cap cap,
1072 void *pval)
1073 {
1074 struct wasapi_stream *strm = (struct wasapi_stream*)s;
1075
1076 PJ_UNUSED_ARG(strm);
1077
1078 PJ_ASSERT_RETURN(s && pval, PJ_EINVAL);
1079
1080 if (cap == PJMEDIA_AUD_DEV_CAP_INPUT_LATENCY &&
1081 (strm->param.dir & PJMEDIA_DIR_CAPTURE))
1082 {
1083 /* Recording latency */
1084 *(unsigned*)pval = strm->param.input_latency_ms;
1085 return PJ_SUCCESS;
1086
1087 } else if (cap == PJMEDIA_AUD_DEV_CAP_OUTPUT_LATENCY &&
1088 (strm->param.dir & PJMEDIA_DIR_PLAYBACK))
1089 {
1090 /* Playback latency */
1091 *(unsigned*)pval = strm->param.output_latency_ms;
1092 return PJ_SUCCESS;
1093
1094 } else if (cap == PJMEDIA_AUD_DEV_CAP_OUTPUT_VOLUME_SETTING)
1095 {
1096 /* Output volume setting */
1097 *(unsigned*)pval = 0; // retrieve output device's volume here
1098 return PJ_SUCCESS;
1099
1100 } else {
1101 return PJMEDIA_EAUD_INVCAP;
1102 }
1103 }
1104
1105 /* API: set capability */
1106 static pj_status_t wasapi_stream_set_cap(pjmedia_aud_stream *s,
1107 pjmedia_aud_dev_cap cap,
1108 const void *pval)
1109 {
1110 struct wasapi_stream *strm = (struct wasapi_stream*)s;
1111
1112 PJ_UNUSED_ARG(strm);
1113 PJ_UNUSED_ARG(cap);
1114
1115 PJ_ASSERT_RETURN(s && pval, PJ_EINVAL);
1116
1117 return PJMEDIA_EAUD_INVCAP;
1118 }
1119
1120 /* API: Start stream. */
1121 static pj_status_t wasapi_stream_start(pjmedia_aud_stream *strm)
1122 {
1123 struct wasapi_stream *ws = (struct wasapi_stream*)strm;
1124 HRESULT hr = E_FAIL;
1125 pj_status_t status = PJ_SUCCESS;
1126
1127 PJ_ASSERT_RETURN(ws != NULL, PJ_EINVAL);
1128
1129 TRACE_((THIS_FILE, "Starting wasapi audio stream"));
1130
1131 if (ws->default_pb_dev) {
1132 hr = ws->default_pb_dev->Start();
1133 EXIT_ON_ERROR(hr);
1134 }
1135
1136 if (ws->default_cap_dev) {
1137 hr = ws->default_cap_dev->Start();
1138 EXIT_ON_ERROR(hr);
1139 }
1140
1141 /* Create and start the thread */
1142 if (!ws->thread) {
1143 status = pj_thread_create(ws->pool, "wasapi", &wasapi_dev_thread, strm,
1144 0, 0, &ws->thread);
1145
1146 if (status != PJ_SUCCESS) {
1147 PJ_LOG(4, (THIS_FILE, "Error creating wasapi thread:%d", status));
1148 }
1149 }
1150
1151 on_exit:
1152 if (status != PJ_SUCCESS) {
1153 PJ_LOG(4, (THIS_FILE, "Error starting wasapi:0x%x", hr));
1154 wasapi_stream_stop(&ws->base);
1155 }
1156
1157 return status;
1158 }
1159
1160 /* API: Stop stream. */
1161 static pj_status_t wasapi_stream_stop(pjmedia_aud_stream *strm)
1162 {
1163 struct wasapi_stream *ws = (struct wasapi_stream*)strm;
1164 HRESULT hr, hr_tmp;
1165 hr = hr_tmp = S_OK;
1166
1167 PJ_ASSERT_RETURN(ws != NULL, PJ_EINVAL);
1168
1169 if (ws->default_pb_dev) {
1170 hr = ws->default_pb_dev->Stop();
1171 if (FAILED(hr)) {
1172 PJ_LOG(4, (THIS_FILE, "Error stopping wasapi playback stream:0x%x",
1173 hr));
1174 } else {
1175 PJ_LOG(4,(THIS_FILE, "Stopped wasapi playback stream"));
1176 }
1177 }
1178
1179 if (ws->default_cap_dev) {
1180 hr_tmp = ws->default_cap_dev->Stop();
1181 if (FAILED(hr_tmp)) {
1182 hr = hr_tmp;
1183 PJ_LOG(4, (THIS_FILE, "Error stopping wasapi capture stream:0x%x",
1184 hr));
1185 } else {
1186 PJ_LOG(4,(THIS_FILE, "Stopped wasapi capture stream"));
1187 }
1188 }
1189
1190 if (FAILED(hr)) {
1191 return PJMEDIA_EAUD_WASAPI_ERROR;
1192 }
1193
1194 return PJ_SUCCESS;
1195 }
1196
1197 /* API: Destroy stream. */
1198 static pj_status_t wasapi_stream_destroy(pjmedia_aud_stream *strm)
1199 {
1200 struct wasapi_stream *ws = (struct wasapi_stream*)strm;
1201
1202 PJ_ASSERT_RETURN(ws != NULL, PJ_EINVAL);
1203
1204 wasapi_stream_stop(strm);
1205
1206 /* Stop stream thread */
1207 if (ws->thread) {
1208 SetEvent(ws->quit_event);
1209 pj_thread_join(ws->thread);
1210 pj_thread_destroy(ws->thread);
1211 ws->thread = NULL;
1212 }
1213
1214 /* Close thread quit event */
1215 if (ws->quit_event) {
1216 CloseHandle(ws->quit_event);
1217 ws->quit_event = NULL;
1218 }
1219
1220 /* Close playback event */
1221 if (ws->pb_event) {
1222 CloseHandle(ws->pb_event);
1223 ws->pb_event = NULL;
1224 }
1225
1226 /* Close capture event */
1227 if (ws->cap_event) {
1228 CloseHandle(ws->cap_event);
1229 ws->cap_event = NULL;
1230 }
1231
1232 /* Release playback device */
1233 if (ws->default_pb_dev) {
1234 ws->default_pb_dev->Release();
1235 ws->default_pb_dev = NULL;
1236 }
1237
1238 /* Release capture device */
1239 if (ws->default_cap_dev) {
1240 ws->default_cap_dev->Release();
1241 ws->default_cap_dev = NULL;
1242 }
1243
1244 /* Release playback volume interface */
1245 if (ws->pb_volume) {
1246 ws->pb_volume->Release();
1247 ws->pb_volume = NULL;
1248 }
1249
1250
1251 #if defined(USE_ASYNC_ACTIVATE)
1252 /* Release audio activator */
1253 if (ws->cap_aud_act) {
1254 ws->cap_aud_act = nullptr;
1255 }
1256
1257 if (ws->pb_aud_act) {
1258 ws->pb_aud_act = nullptr;
1259 }
1260
1261 if (ws->cap_id) {
1262 ws->cap_id = nullptr;
1263 }
1264
1265 if (ws->pb_id) {
1266 ws->pb_id = nullptr;
1267 }
1268 #else
1269 if (ws->cap_id) {
1270 CoTaskMemFree((LPVOID)ws->cap_id);
1271 }
1272
1273 if (ws->pb_id) {
1274 CoTaskMemFree((LPVOID)ws->pb_id);
1275 }
1276 #endif
1277
1278 pj_pool_release(ws->pool);
1279
1280 return PJ_SUCCESS;
1281 }
1282
1283 #if defined(USE_ASYNC_ACTIVATE)
1284 HRESULT AudioActivator::ActivateCompleted(
1285 IActivateAudioInterfaceAsyncOperation *pAsyncOp)
1286 {
1287 HRESULT hr = S_OK, hr2 = S_OK;
1288 IUnknown *aud_interface = NULL;
1289 IAudioClient2 *aud_client = NULL;
1290
1291 hr = pAsyncOp->GetActivateResult(&hr2, &aud_interface);
1292 if (SUCCEEDED(hr) && SUCCEEDED(hr2)) {
1293 aud_interface->QueryInterface(IID_PPV_ARGS(&aud_client));
1294 if (aud_client)
1295 {
1296 pj_thread_desc thread_desc;
1297 pj_thread_t *act_thread;
1298 pj_bzero(thread_desc, sizeof(pj_thread_desc));
1299
1300 if (!pj_thread_is_registered()) {
1301 pj_thread_register("activator", thread_desc, &act_thread);
1302 }
1303 }
1304 }
1305
1306 task_completed.set(aud_client);
1307 return hr;
1308 }
1309
1310 #endif
1311
1312 #endif /* PJMEDIA_AUDIO_DEV_HAS_WASAPI */